首页 > 解决方案 > 为什么我会陷入无休止的重定向循环?

问题描述

我安装了基本的 Yii2 应用程序并希望强制所有连接使用 HTTPS 而不是 HTTP。这是我的.htaccess:

RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=301]

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteRule (.+)/$ /$1 [L,R=301]
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index\.html
RewriteRule ^(.*)index.html /$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/main\.html
RewriteRule ^(.*)main.html /$1 [R=301,L]

# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Otherwise forward the request to index.php
RewriteRule . index.php

在 web/index.php 我添加

$_SERVER['HTTPS']='on';

当我打开网站时,我看到一个错误“重定向太多”。我检查了 chrome 网络检查器,我从https://example.org看到我正在重定向到https://example.org,因此进入了循环

标签: phpapacheyii2

解决方案


我使用以下代码将 http 重定向到 .htaccess 文件中的 https

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example/$1 [R=301,L]

它将端口 80 上的所有请求重定向到 https。


推荐阅读