重定向到HTTPS会返回错误"重定向太多"

Mik*_*ke 7 .htaccess redirect

我试图通过htaccess强制https,并得到"太多的重定向"错误.以下是我用来尝试实现此目的的方法.

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Run Code Online (Sandbox Code Playgroud)

关于我如何能够实现这一目标或者为什么这样做似乎不起作用的任何想法?

编辑:我按照这里的答案强制https:// www.对于带有mod_rewrite的htaccess中的Codeigniter, 它似乎正在为我引起重定向循环.当我删除这部分时:

RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Run Code Online (Sandbox Code Playgroud)

重定向循环消失; 但它不会重定向到https.

小智 17

我不能确定这是否与某个(或某些)托管服务提供商有关,但没有一个解决方案适合我.由于主机提供商的限制,我无法获得apache版本,除了它是2.x.

这是做了什么,也许对某人有帮助:

RewriteEngine On
RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Run Code Online (Sandbox Code Playgroud)


小智 1

正如 RiggsFolly 所提到的,该语句存在问题,但如果这不起作用,您可以尝试在 head 标签中强制使用它:

$use_sts = true;

// iis sets HTTPS to 'off' for non-SSL requests
if ($use_sts && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
    header('Strict-Transport-Security: max-age=31536000');
} elseif ($use_sts) {
    header('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], true, 301);
    // we are in cleartext at the moment, prevent further execution and output
    die();
}``
Run Code Online (Sandbox Code Playgroud)