right order of rewrite rules in an htaccess file

时间秒杀一切 提交于 2019-12-23 03:04:49

问题


I need to have :

http://www.example.com/v1/my-project/ redirected to http://example.com/my-project/

so :

(1) remove the www from the http_host

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

(2) remove the 'v1/' part of the request_uri

RewriteCond %{REQUEST_URI} ^/v1/(.*)$ [NC]
RewriteRule . %1 [R=301,L]

(3) I also want to redirect all 404 to the homepage.

ErrorDocument 404 /

(4) Finally, all my documents actually reside in a "v2/" folder which hosts the current active website, but i don't want "v2" in the url, just "/"

RewriteCond %{REQUEST_URI} !^/v2/ [NC]
RewriteRule ^(.*)$ /v2/$1 [NC,L]

So, here are my rules. My question is: i don't manage (2): it gets redirected to / (because of rule (3) i guess. I think the order of my rules must be faulty but i can't seem to get it right. Can you help ?


回答1:


"Rule 3" isn't a rule at all, and its order relative to your RewriteRules doesn't matter. Rule 2 is failing for some other reason. I'm not sure whether it will address your problem, but I would simplify your rules somewhat by writing them like this:

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

RewriteRule ^v1/(.*) /$1 [R=301,L,NC]

RewriteCond %{REQUEST_URI} !^/v2/ [NC]
RewriteRule (.*) /v2/$1 [NC,L]



回答2:


You should first write any rule that is causing an external redirect (R flag) and then the other rules. Otherwise an already rewritten URL can be used for an external redirect though it was just intended for an internal redirect.

So I won’t change the order you have right now.



来源:https://stackoverflow.com/questions/1108995/right-order-of-rewrite-rules-in-an-htaccess-file

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