Remove double 301 redirect from my htaccess?

别来无恙 提交于 2019-12-24 16:51:49

问题


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.



来源:https://stackoverflow.com/questions/36328628/remove-double-301-redirect-from-my-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!