htaccess重写 - 防止多重重定向

时间:2013-11-14 02:23:26

标签: regex apache .htaccess mod-rewrite url-rewriting

以下正则表达式完全有效,除非在用户转到examplesite1.com/site1的情况下。发生这种情况时,页面会因多次重定向而失败,并且会继续将request=site1查询添加到URL。我认为添加RewriteCond %{ENV:REDIRECT_STATUS} ^$会解决这个问题,但似乎并非如此。

此设置适用于多域网站。 site1,site2和shared三个文件夹。还存在未显示的site2和shared的重写规则,因为它们不会影响此问题。

# if the resource exists in site1 return it to the user
RewriteCond %{HTTP_HOST} examplesite1.com$
RewriteCond %{DOCUMENT_ROOT}/site1/%{REQUEST_URI} -f
RewriteRule ^(.*)$ /site1/$1 [QSA,L]

# no file found, send URI to CMS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?request=$1 [QSA,L]

完成.htaccess文件:

AddDefaultCharset UTF-8
# Disallow browsing file directories
Options -Indexes 

RewriteEngine on
RewriteBase /

#remove the trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} (.*)/$
RewriteRule ^(.+)/$ /$1 [R=301,L]

RewriteCond %{HTTP_HOST} examplesite1.com$
RewriteCond %{DOCUMENT_ROOT}/site1/%{REQUEST_URI} -f
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.*)$ /site1/$1 [QSA,L]

RewriteCond %{HTTP_HOST} examplesite2.com$
RewriteCond %{DOCUMENT_ROOT}/site2/%{REQUEST_URI} -f
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.*)$ /site2/$1 [QSA,L]

RewriteCond %{DOCUMENT_ROOT}/shared/%{REQUEST_URI} -f
RewriteRule ^(.*)$ /shared/$1 [QSA,L]

# resources not to be public are sent to CMS
RewriteCond %{REQUEST_FILENAME} (\.inc\.|\.tpl$)
RewriteRule ^(.*)$ /index.php?request=$1 [QSA,L]

# no resource found, send URI to CMS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.*)$ /index.php?request=$1 [QSA,L]

1 个答案:

答案 0 :(得分:0)

尝试添加额外条件:

RewriteCond %{HTTP_HOST} examplesite1.com$
RewriteCond %{REQUEST_URI} !^/site1/
RewriteCond %{DOCUMENT_ROOT}/site1/%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/site1/%{REQUEST_URI} -d
RewriteRule ^(.*)$ /site1/$1 [QSA,L]

这里可能发生的情况是,您需要在应用其他规则之后阻止重定向发生。请尝试在 RewriteBase /下面添加

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]