Home > Back-end >  Redirect a URL with two query string parameters to a new domain with a changed path using Apache
Redirect a URL with two query string parameters to a new domain with a changed path using Apache

Time:05-10

I'm trying to do the following thing:

Transform URL: https://example.com/human/?system=jitsi&action=SYSTEM

to: https://new.example/?action=SYSTEM&system=jitsi

RewriteEngine On
RewriteCond %{REQUEST_METHOD}   GET
RewriteCond "%{QUERY_STRING}" action=(. ) 
RewriteRule / https://new.example/?action=SYSTEM&system=%1?

Unfortunately I can't get the expected result.

CodePudding user response:

Your rules have several problems:

  • You aren't matching the human/ in the URL path that you are trying to remove.
  • Neither your condition nor your rule has regex markers for "starts with" (^) or "ends with" ($) which means that they are matching substrings rather than full strings.
  • Your rule starts with a slash which means that it can't be used in .htaccess, only in Apache's conf files. I recommend starting rules with an optional slash /? so that they can be used in either context.
  • Your query string condition is only matching one of the two parameters that you say need to be present to redirect.
  • (. ) in your query string condition can match too much. It would include other parameters separated by an ampersand (&). This should be changed to ([^&] ) meaning "at least one character not including ampersands"
  • You have an extra stray ? at the end of your target URL that would be interpreted as part of the value of the system parameter.
  • You don't explicitly specify flags for redirect ([R]) or last ([L]) which are best practice to include.
RewriteEngine On
RewriteCond %{REQUEST_METHOD}   GET
RewriteCond %{QUERY_STRING} ^system=([^&] )&action=([^&] )$
RewriteRule ^/?human/$ https://new.example/?action=%2&system=%1 [R,L]
  • Related