Remove double 301 redirect from my htaccess?

2019-08-13 21:31发布

问题:

I just realized that my htaccess produces double 301 redirect in some cases. For example, if you try to access http://example.com/old_url it will:

  • First 301 to http://www.example.com/old_url (added www)
  • Then 301 to http://www.example.com/new_url (changed to new url)

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?

回答1:

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.