Ssl
強制 HTTPS 時的重定向循環
我正在使用以下內容在我的主網站上強制使用 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,如下所示:### Force HTTPS RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
我希望以上內容在嘗試在 Amazon Web Services 負載均衡器後面強制使用 HTTPS 時對其他人有所幫助。