.htaccess强制HTTPS

时间:2016-06-08 18:07:26

标签: php apache .htaccess mod-rewrite

我一直在努力寻找使用.htaccess在我的网站上强制使用HTTPS的方法。我试过的任何方式都会导致重定向循环。我找到了一个PHP替代方案并对其进行了修改以适应我的网络服务器,但如果有人可以提供帮助,我会喜欢.htaccess等效。

if ($_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    header("HTTP/1.1 301 Moved Permanently");
    $location = "https://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
    header("Location: $location");
    exit;
}

1 个答案:

答案 0 :(得分:5)

您可以在根目录中使用此规则.htaccess:

RewriteEngine On

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301,NE]