我试图说服mod-rewrite将http://example.com重定向到https://example.com但不重定向http://subdomain.example.com
我已将以下内容添加到网站根目录中的.htaccess文件中,
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
那(我认为会这样)重定向所有内容,然后我尝试了
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^http://example(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}
但这似乎也会重定向一切?
答案 0 :(得分:1)
RewriteRule仅匹配主机和端口之后(在VirtualHost上下文中)或相对文件系统路径(在Directory / htaccess上下文中)的URL部分;因此,尝试匹配RewriteRule中的主机名将无效。
但是%{HTTP:Host}
会为您提供Host
HTTP标头,以便RewriteCond可以匹配它:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:Host} =example.com
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R]
缺点是mod_rewrite会注意到您根据HTTP标头有条件地重写,并且会添加Vary: Host
标头。如果您不想这样,可以先将它存储到变量中,然后对该变量执行RewriteCond:
RewriteRule . - [E=HTTP_HOST_NO_VARY:%{HTTP:Host}]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{ENV:HTTP_HOST_NO_VARY} =example.com
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R]