Way to Redirect a URL via .htaccess

vanek988

New member
for SEO the best way is:
PHP:
Options +FollowSymLinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^oldsite\.com
RewriteRule ^(.*)$ http://newsite.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.oldsite\.com
RewriteRule ^(.*)$ http://newsite.com/$1 [R=301,L]
 

Peter

Member
I have a hard time debugging rewrite rules in my head so I assume the above codes are correct.

The first one, posted by melchor, will redirect all requests so it should only be used if the new domain is stored elsewhere. If both domains point to the same location on the server this code would create an infinite redirection loop.

The second one, posted by vanek988, works the same except that it only redirects if the domain name is correct. This can be used to redirect an old domain to a new domain, or the www version of the domain to the non-www version (or vice versa).
 

fouadChk

Member
Peter said:
I have a hard time debugging rewrite rules in my head so I assume the above codes are correct.
Well, let's see :)

Peter said:
The first one, posted by melchor, will redirect all requests so it should only be used if the new domain is stored elsewhere. If both domains point to the same location on the server this code would create an infinite redirection loop.
Indeed Peter. The OP isn't very helpful in anyway. The only use case for it is (as far as I can see) when one is hosting one domain on his server and wants for some odd reasons to redirect all the incoming requests (which are assumed to be targeting it) to somewhere else. Doesn't make much practical sense.

Peter said:
The second one, posted by vanek988, works the same except that it only redirects if the domain name is correct. This can be used to redirect an old domain to a new domain, or the www version of the domain to the non-www version (or vice versa).
It's the sensible way of doing what the OP was thinking has solved. In other words, it checks for the domain part of requests instead of blindly/systematically performing redirects. A more contracted version would be:
Code:
<ifModule mod_rewrite.c>
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?oldsite\.com$ [NC]
RewriteRule ^(.*)$ http://newsite.com/$1 [L,R=301] 
</ifModule>

You would also note the use use of the [NC] flag to normalize capitalization (although modern browsers are all converting it to lower case before sending the requests.)
 

smalpierre

New member
The best way is to do it in DNS, or in the Apache config file. .htacecss is slow, I use AllowOverride none in production to turn it off.