Home > Enterprise >  RewriteRule to handle one domain two folders to two domains no folder
RewriteRule to handle one domain two folders to two domains no folder

Time:10-21

I am attempting to create rewrite rules to handle some specific website redirections:

I would like domain1.ca/folder1/xyz to go to domain2.ca/xyz and domain1.ca/folder2/xyz to go to domain3.ca/xyz

Right now my attempts are as following:

RewriteCond %{HTTP_HOST} ^domain1.ca$ [OR]
RewriteCond %{HTTP_HOST} ^www.domain1.ca$
RewriteRule ^(\/folder1\/)(.*)$ "https://domain2.ca/$1" [R=301,L]

RewriteCond %{HTTP_HOST} ^domain1.ca$ [OR]
RewriteCond %{HTTP_HOST} ^www.domain1.ca$
RewriteRule ^(\/folder2\/)(.*)$ "https://domain3.ca/$1" [R=301,L]

Any help would be greatly appreciated :) Thx.

CodePudding user response:

A couple of problems with your existsing rules:

  • In .htaccess the URL-path matched by the RewriteRule pattern does not start with a slash. So, the URL-path starts folder1/xyz, not /folder1/xyz.

  • You are unnecessarily capturing "folder1" in the first parenthesised subpattern and using this in the substitution string (ie. $1). You should be using $2, or don't capture the first path segment.

The directives could also be tidied up a bit (eg. no need to backslash-escape slashes in the regex and the conditions can be combined).

Try the following instead:

RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.ca [NC]
RewriteRule ^folder1/(.*) https://domain2.ca/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.ca [NC]
RewriteRule ^folder2/(.*) https://domain3.ca/$1 [R=301,L]

Additional notes:

  • The end-of-string anchor ($) following (.*)$ in the RewriteRule pattern is not required since regex is greedy by default.
  • You only need to surround the argument in double quotes if it contains spaces.
  • I removed the end-of-string anchor ($) from the end of the CondPattern to also match fully qualified domain names that end in a dot.
  • I added the NC flag to the condition. It's technically possible that some bots can send a mixed/uppercase Host header.

Test first with 302 (temporary) redirects to avoid potential caching issues.

  • Related