.htaccess内部重定向问题

时间:2014-11-23 16:08:10

标签: regex apache .htaccess mod-rewrite redirect

使用我的.htaccess文件时,如果存在某种条件,则会创建某种规则循环。以下是有问题的代码:

<IfModule mod_rewrite.c>
RewriteEngine On

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule ^(.+)/?$ /%1.php?o=$1 [L,NC,QSA]

RewriteCond %{HTTP_HOST} ^(.*)\.example\.com$ [NC]
RewriteRule ^$ /%1.php [L,NC,QSA]
</IfModule>

通常这样做是:

test.example.com -> example.com/test.php
test.example.com/test2 -> example.com/test.php?o=test2

很好,除非“测试”子域部分指向不存在的文件,否则会出现内部重定向错误,特别是:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace., referer: [retracted]

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

是的,它会导致循环,因为当RewriteCond %{REQUEST_FILENAME} !-f不存在时/test.php /test.php仍然属实。

您可以使用此代码来阻止循环:

<IfModule mod_rewrite.c>
RewriteEngine On

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

# don't redirect after one internal redirect
RewriteCond %{ENV:REDIRECT_STATUS} .+
RewriteRule ^ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule ^(.+?)/?$ /%1.php?o=$1 [L,QSA]

RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule ^$ /%1.php [L]
</IfModule>