Search code examples
apache.htaccessmod-rewrite

Redirect via htaccess and remove part of link


I like to redirect my website.

Now I have:

https://www.old.example/NL/page

And it has to become

https://www.new.example/page

I know I can change the domain with

Normaly I would use something like this, but this would only change the domain:

 RewriteCond %{HTTP_HOST} ^old.example/NL$ [OR]
  RewriteCond %{HTTP_HOST} ^www.old.example/NL/$
  RewriteRule (.*)$ https://www.new.example/$1 [R=301,L]

So now I am thinking of something like this:

 RewriteRule %{HTTP_HOST} ^old.example/(NL)/([A-Za-z0-9_-]*)$ http://www.new.example/$2&%{QUERY_STRING} [R=301,L]

But this gives the following result: http://www.new.example/NL/page

Can anyone help me with the right solution?


Solution

  • The HTTP_HOST server variable contains the value of the requested Host header (ie. the hostname), this does not contain the URL-path, so neither of your rules will do anything (in fact, the second rule is entirely invalid).

    You can do something like the following instead:

    RewriteCond %{HTTP_HOST} ^(www\.)?old\.example [NC]
    RewriteRule ^NL/(.*) https://www.new.example/$1 [R=301,L]
    

    All Apache server variables of the form HTTP_<NAME> refer to the HTTP request header for the corresponding <NAME>.