我正在使用以下内容在我的主网站上强制使用 HTTPS。
### Force SSL
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
如果你想查看完整的 htaccess 文件,我把它放在下面:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
### Blacklist via Referrers
RewriteCond %{HTTP_REFERER} removed\.net [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.com [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.removed\.com [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.com [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.net [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.sx [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.com [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.com [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.com [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.com [NC,OR]
RewriteCond %{HTTP_REFERER} removed\.org [NC]
RewriteRule ^(.*)$ - [F,L]
### Force SSL
#RewriteCond %{HTTPS} !=on
#RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### Canonicalize codeigniter URLs
# If your default controller is something other than
# "welcome" you should probably change this
RewriteRule ^(welcome(/index)?|index(\.php)?)/?$ / [L,R=301]
RewriteRule ^(.*)/index/?$ $1 [L,R=301]
# Removes trailing slashes (prevents SEO duplicate content issues)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ $1 [L,R=301]
# Enforce NO www
RewriteCond %{HTTP_HOST} ^www [NC]
RewriteRule ^(.*)$ https://removed.com/$1 [L,R=301]
# Removes access to the system folder by users.
# Additionally this will allow you to create a System.php controller,
# previously this would not have been possible.
# 'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]
# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# Without mod_rewrite, route 404's to the front controller
ErrorDocument 404 /index.php
</IfModule>
我正在努力弄清楚重定向循环是如何发生的。
更新
我没有明确说明我的 Web 服务器 (Apache) 仅在端口 80 上配置了一个虚拟主机,该主机将 HTTP 和 HTTPS 流量通过负载平衡器定向到它。负载平衡器处理 SSL 连接。
感谢HBruijn 的评论,我明白了为什么我得到了重定向循环。
来自 ELB 的流量将始终是 HTTP,因为它处理到用户的 HTTPS 流量,但到服务器的流量是 HTTP,所以我之前的规则将导致循环。
经过一些研究,我发现负载均衡器会转发一些有用的标头,例如
X-Forwarded-Proto
. 这可用于确定客户端是使用 HTTP 还是 HTTPS,如下所示:我希望以上内容在尝试在 Amazon Web Services 负载均衡器后面强制使用 HTTPS 时对其他人有所帮助。
无需在文件中执行此
.htaccess
操作,只需在 Apache 配置的非 SSL VirtualHost 条目中设置 SSL重定向:这更有效。
另外:我的烦恼,引自.htaccess文件手册: