Home > other >  Redirect old domain to new domain - Rewriterule
Redirect old domain to new domain - Rewriterule

Time:09-18

Following are the redirection rule I have in my htaccess file. They redirect https://olddomain.com to https://subdomain.domain.com but the web pages are not getting redirected. I still have olddomain.com/page1 loading.

`RewriteCond %{HTTP_HOST} ^old\.com$ [OR]
 RewriteCond %{HTTP_HOST} ^www\.old\.com$ 
 RewriteRule ^/?$ "https\:\/\/subdomain\.domain\.com\/" [R=301,L]`

I added the following rule which is working partially, the slash after the domain is missing. Now the redirect is https://subdomain.domain.compage1 instead of https://subdomain.domain.com/page1

RewriteRule ^ https\:\/\/subdomain\.domain\.com\/{REQUEST_URI} [L,R=301]

How to fix this. Any help please. (I tried the redirect without escaping \ at the end but this didn't work.

RewriteRule ^ https\:\/\/subdomain\.domain\.com{REQUEST_URI} [L,R=301])

CodePudding user response:

RewriteCond %{HTTP_HOST} ^old\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.old\.com$ 
RewriteRule ^/?$ "https\:\/\/subdomain\.domain\.com\/" [R=301,L]

These redirect the homepage (root directory) only. To redirect any URL-path to the same URL-path at the target use the following instead:

RewriteCond %{HTTP_HOST} ^(www\.)?old\.com [NC]
RewriteRule ^ https://subdomain.domain.com%{REQUEST_URI} [R=301,L]

I've combined your two conditions.

Note that the syntax is %{REQUEST_URI} (with a % prefix) to reference the REQUEST_URI server variable. "{REQUEST_URI}" is otherwise just literal text.

There is no need to backslash-escape all those characters in the substition string.

Clear your browser cache before testing. And preferably test with 302 (temporary) redirects to avoid potential caching issues.


I added the following rule which is working partially, the slash after the domain is missing. Now the redirect is https://subdomain.domain.compage1 instead of https://subdomain.domain.com/page1

RewriteRule ^ https\:\/\/subdomain\.domain\.com\/{REQUEST_URI} [L,R=301]

Except that that is not possible with the directive as stated - you were perhaps seeing a cached response as a result of earlier erroneous redirects. 301 (permanent) redirects are cache persistently by the browser. Always test with 302 (temporary) redirects and ideally with the browser cache disabled (option on the "Network" tab) of the browser dev tools.


UPDATE:

Alternative solution

This would need to go in the root .htaccess file (it would not work if it is in a subdirectory .htaccess, unlike the rule above).

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

This uses a backreference instead of the REQUEST_URI server variable.

This redirect needs to go near the top of the .htaccess file, before most other directives.

Make sure you've cleared your browser cache before testing.

  • Related