.htaccess条件:https问题

时间:2017-11-02 10:13:12

标签: .htaccess mod-rewrite

不久前,我问过一些关于.htaccess规则的问题 有人非常善良并且给了我以下内容:

RewriteEngine On
RewriteBase /

# Force https and non-www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Redirect /index.htm to /home and avoids infinite redirect loop
RewriteCond %{THE_REQUEST} \s/index\.htm\s [NC]
RewriteRule ^ /home [R=301,L]

# Rewrite (internally) /home to /index.htm
RewriteRule ^home$ /index.htm [L]

# Redirect (if not an existing file) to /index.htm (which will after redirect to /home)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.htm [R=301,L]

我觉得它工作得很好,但我有一些问题:

https://example.com/
https://example.com/home  
https://example.com/index.htm 
https://www.example.com/
https://www.example.com/home
https://www.example.com/index.htm  

- 重定向到https://example.com/home的所有变体都正常工作

http://example.com/ -> https://home (in Chrome) / error (in Firefox)  
http://example.com/home -> https://home (in Chrome) / error (in Firefox)   
http://example.com/index.htm -> https://index.htm  
http://www.example.com/ -> error
http://www.example.com/home -> https://home (in Chrome) / error (in Firefox)    
http://www.example.com/index.htm -> https://index.htm  

- 根本不工作

我认为它可能是由[L]标志引起的,但我无法想象如何解决这个问题。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的第一条规则存在问题,因为您试图在RewriteCond条款之后从OR获取值。

您可以使用以下规则:

RewriteEngine On
RewriteBase /

# Force https and non-www
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

# Redirect /index.htm to /home and avoids infinite redirect loop
RewriteCond %{THE_REQUEST} \s/index\.htm\s [NC]
RewriteRule ^ /home [R=301,L]

# Rewrite (internally) /home to /index.htm
RewriteRule ^home/?$ /index.htm [L,NC]

# Redirect (if not an existing file) to /index.htm (which will after redirect to /home)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /home [R=301,L]

确保在测试此更改之前清除浏览器缓存。