RewriteCond不适用于HTTP_HOST的强制https

n1c*_*la5 4 regex apache .htaccess mod-rewrite https

我正在尝试编写一个条件,该条件将在实时主机名(domain.com)上强制使用https,但如果在我们的本地测试主机名(domain.local)上则不这样做。

这是我所拥有的:

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

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

我也尝试过使用这种条件来代替在.local或.com上不做任何事情的中间条件:

RewriteCond %{HTTP_HOST} ^domain\.com [NC]
Run Code Online (Sandbox Code Playgroud)

这是我的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]
Run Code Online (Sandbox Code Playgroud)

谢谢

小智 5

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

一段时间,https标志不起作用。不知道为什么。但是我找到了使用ENV:HTTPS的解决方案。这对我来说是停止重定向循环。


anu*_*ava 4

您需要将底部http->https规则移动到 .htaccess 的顶部,就在该行下方RewriteBase /。还可以使用这个稍微修改过的规则:

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

  • 就我而言,我需要使用 RewriteCond %{ENV:HTTPS} !=on。因此,下面提到的环境变量特别是“!= on”而不是“off”。 (2认同)