How avoid infinite loop when htaccess rewrites to a copy of same htaccess-file?

瘦欲@ 提交于 2019-12-25 01:25:53

问题


I have this htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} =test.example.com [NC]
RewriteRule ^((?!test/).*)$ test/$1 [L,NC]

And a completely identical copy of the same file in the "test" directory. So, of course, this leads to an infinite loop when the first file pass you to the second file running the rules again.

I have tried add the rule RewriteCond %{REQUEST_URI} !^test [L,NC] in hope that REQUEST_URI stood for the real path and not the new "alias". However, it didn't worked.

Is there any way to maybe check which directory we are in to use in a condition? Or any other solution to this problem? With the basis to keep the both file's codes identical.


回答1:


If you're already in test directory there is no point to rewrite again to test directory using a relative path. It will be better to determine the RewriteBase dynamically and use absolute paths for rewriting:

RewriteEngine On

# generate BASE dir in env variable %{ENV:BASE}
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} =test.example.com [NC]
RewriteRule ^(.*)$ %{ENV:BASE}test/$1 [L,NC]

RewriteCond %{ENV:REDIRECT_STATUS} ^$ is used to prevent rewriting after first rewriting of the rule since %{ENV:REDIRECT_STATUS} becomes 200 after that.




回答2:


Okay, weird, but I now got it to work - simply like this:

RewriteCond %{HTTP_HOST} =test.example.com [NC]
RewriteCond %{REQUEST_URI} !test [NC]
RewriteRule ^((?!test/).*)$ test/$1 [L,NC]

Edit: Seems like it only works for the startpage. On other pages, the beginning trailing slash of the path is being removed.



来源:https://stackoverflow.com/questions/26776310/how-avoid-infinite-loop-when-htaccess-rewrites-to-a-copy-of-same-htaccess-file

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