RewriteCond没有为HTTP_HOST强制使用https

时间:2014-04-29 14:03:06

标签: regex apache .htaccess mod-rewrite https

我正在尝试写一个强制https在实际主机名(domain.com)上的条件,但是如果它在我们的本地测试主机名(domain.local)上则不会。

这就是我所拥有的:

#force https
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !domain\.local [NC]
RewriteRule ^(.*?)$ https://www.domain.com/$1 [L,R=301]

此条件会重写为https,但也会将domain.local重定向到domain.com

我也试过这个条件代替中间条件,它在.local或.com上没有做任何事情:

RewriteCond %{HTTP_HOST} ^domain\.com [NC]

以下是我的htaccess文件的完整内容

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

#force ssl
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L,NE]

#rewrite payments subdomain
RewriteCond %{HTTP_HOST} ^payments\.domain\.local$ [NC]
RewriteRule ^(.*)$ https://otherdomain.com/dmi_domain.htm [NC,R=301,L]
RewriteCond %{HTTP_HOST} ^payments\.domain\.com$ [NC]
RewriteRule ^(.*)$ https://otherdomain.com/loanadmin/dmi_domain.htm [NC,R=301,L]

#agents folder to subdomain
RewriteCond %{HTTP_HOST} ^agents\.domain\.local$ [NC]
RewriteRule ^agents/(.*)$ /agents/$1 [L,P]
RewriteCond %{HTTP_HOST} ^agents\.domain\.com$ [NC]
RewriteRule ^agents/(.*)$ /agents/$1 [L,P]

#force www for .com
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^payments\. [NC]
RewriteCond %{HTTP_HOST} !^agents\. [NC]
RewriteCond %{HTTP_HOST} !^domain\.local
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_URI} !^/questions/
RewriteRule ^(.*?)$ https://www.%{HTTP_HOST}/$1 [L,R=301]

#force www for .local
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^payments\. [NC]
RewriteCond %{HTTP_HOST} !^agents\. [NC]
RewriteCond %{HTTP_HOST} !^domain\.com
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_URI} !^/questions/
RewriteRule ^(.*?)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

#force trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_URI} !^/rate-panel/xml/
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_URI} !^/questions/
RewriteRule ^(.*)$ $1/ [L,R=301]

#get rid of index.php in url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_URI} !^/questions/
RewriteRule ^(.*)$ /index.php/$1 [L]

感谢

2 个答案:

答案 0 :(得分:4)

你可以使用 RewriteCond %{ENV:HTTPS} off

有些时候https标志无效。不知道为什么。但我找到了使用ENV:HTTPS的解决方案。这为我停止重定向循环。

答案 1 :(得分:3)

您需要将底部http->https规则移至RewriteBase /行下方.htaccess的顶部。也可以使用这个稍微修改过的规则:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !local [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L,NE]