26682

Question:
I just realized that my htaccess produces double 301 redirect in some cases. For example, if you try to access <a href="http://example.com/old_url" rel="nofollow">http://example.com/old_url</a> it will:
<ul><li>First 301 to <a href="http://www.example.com/old_url" rel="nofollow">http://www.example.com/old_url</a> (added www)</li> <li>Then 301 to <a href="http://www.example.com/new_url" rel="nofollow">http://www.example.com/new_url</a> (changed to new url)</li> </ul>Here's how my htaccess is set up:
RewriteEngine On
# Add www
RewriteCond %{HTTP_HOST} ^example.com [nocase]
RewriteRule ^(.*) http://www.example.com/$1 [last,redirect=301]
# Do some url rewriting
RewriteRule ^new_url_1$ new_url_1.php [NC,L]
RewriteRule ^new_url_2$ new_url_2.php [NC,L]
# Do the 301 redirections
Redirect 301 /old_url_1 http://www.example.com/new_url_1
Redirect 301 /old_url_2 http://www.example.com/new_url_2
How can I fix that to have only one 301 for better SEO?
Answer1:Don't mix Redirect
directives with mod_rewrite
rules and keep specific redirect rules before www
rule:
RewriteEngine On
## Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [NE,R=302,L]
# Do specific 301 redirections
RewriteRule ^old_url_1$ http://www.example.com/new_url_1 [L,NC,R=301]
RewriteRule ^old_url_2$ http://www.example.com/new_url_2 [L,NC,R=301]
# Add www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=301]
# Do some url rewriting
RewriteRule ^new_url_1$ new_url_1.php [NC,L]
RewriteRule ^new_url_2$ new_url_2.php [NC,L]
Make sure to clear your browser cache before testing.