强制ssl与.htaccess重写地址

时间:2011-08-03 20:12:53

标签: .htaccess

我目前正在使用此.htaccess将带有目录的所有页面请求重定向到我的index.php

RewriteEngine on
RewriteCond $1 !^(index\.php|cas)
RewriteRule ^(.*)$ /seattle/index.php/$1 [L]

这样可以正常工作并生成隐藏index.php的url,我在index.php中有代码可以使url看起来干净。

但现在我需要通过ssl强制页面连接,所以我试过

RewriteEngine on
RewriteCond %{SERVER_PORT} 80
RewriteCond $1 !^(index\.php|cas)
RewriteRule ^(.*)$ https://example.com/seattle/index.php/$1 [L]

它可以强制ssl,但现在它也强制url包含index.php:

https://example.com/seattle/index.php/pagename

而不是我想要的

https://example.com/seattle/pagename

我错过了什么?

1 个答案:

答案 0 :(得分:1)

更改协议(HTTP - > HTTPS)和/或域名(www.example.com - > example.com)正确的重定向(“301永久重定向”或“302 Found / Temp Redirect” )是必需的。

因此,您无法组合重写和重定向,仍然显示原始网址。它必须是2个不同的规则,并且应首先列出用于更改协议/域的规则。例如:

RewriteEngine on

# force HTTPS for all URLs
RewriteCond %{HTTPS} =off
RewriteRule . https://example.com%{REQUEST_URI} [R=301,L]

# other rewrite rules
RewriteCond $1 !^(index\.php|cas)
RewriteRule ^(.*)$ /seattle/index.php/$1 [L]

我添加的规则会将所有 HTTP网址重定向到HTTPS。如果您只需要重定向其中一些 - 通过其他RewriteCond行添加适当的条件。

%{HTTPS}是检查SSL是开启还是关闭的最常见和“正确”方式(但这取决于您的具体情况和服务器配置)。检查%{HTTPS}时,如果您的站点在非标准端口(非80端口)上运行,则可以安全地防止出现这种情况。您可以使用%{SERVER_PORT} =80代替(适用于大多数情况)。

根据上述规则,http://example.com/seattle/pagename的重写将分两步进行:

  1. 301重定向到https://example.com/seattle/pagename
  2. 重写(内部重定向)至/seattle/index.php/pagename