我目前遇到mod_rewrite的无限循环问题。
我想要什么(规则要按顺序应用):
示例:
到目前为止我得到了什么:
RewriteEngine On
# Store protocol (HTTP or HTTPS) as ENV variable
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [OR]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=proto:http]
RewriteCond %{HTTP:CF-Visitor} '"scheme":"https"' [OR]
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=proto:https]
# Stript www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ %{ENV:proto}://%1%{REQUEST_URI} [L,NC,QSA,R=301]
# Directory exists => rewrite
RewriteCond %{REQUEST_URI} !^/%{HTTP_HOST} [NC]
RewriteCond %{HTTP_HOST} -d
RewriteRule ^ %{HTTP_HOST}%{REQUEST_URI} [L,NC,QSA]
# Directory doesn't exist => redirect
RewriteCond %{REQUEST_URI} !^/%{HTTP_HOST} [NC]
RewriteCond %{HTTP_HOST} !-d
RewriteRule ^ %{ENV:proto}://domain.tld%{REQUEST_URI} [L,NC,QSA,R]
我知道所有这些都可以通过虚拟主机实现。不幸的是,我已经在共享的虚拟主机上了.htaccess是我可以使用的所有东西,所以我不得不这样做。
我感谢任何帮助或想法引导我走向正确的方向。
答案 0 :(得分:1)
希望这会有所帮助:
RewriteEngine On
RewriteBase "/"
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=proto:http]
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=proto:https]
# Strip www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ %{ENV:proto}://%1%{REQUEST_URI} [L,NC,QSA,R=301]
#Prevent loop
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
# Directory exists => rewrite
RewriteCond %{DOCUMENT_ROOT}/%{HTTP_HOST} -d
RewriteRule ^ /%{HTTP_HOST}%{REQUEST_URI} [L,NC,QSA]
# Directory doesn't exist => redirect (but not if host=example.com)
RewriteCond %{DOCUMENT_ROOT}/%{HTTP_HOST} !-d
RewriteCond %{HTTP_HOST} !=example.com
RewriteRule ^ %{ENV:proto}://example.com%{REQUEST_URI} [L,NC,QSA,R]