我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?

我用的是PHP。


当前回答

在.htaccess文件中使用以下代码自动将访问者重定向到站点的HTTPS版本:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

如果你有一个现有的。htaccess文件:

不要重复“重写引擎”。

确保以RewriteCond和RewriteRule开头的行立即跟随已经存在的RewriteEngine On。

其他回答

以上内容仅适用于Apache服务器。如果在tomcat上运行PHP会怎样?

所以你可以使用PHP代码,无论是Apache/tomcat/Nginx等…

if (!((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&   
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))){
    $redirect = 'https://' . str_replace($_SERVER['SERVER_PORT'], 8443, $_SERVER['HTTP_HOST']) . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}

在.htaccess文件中使用以下代码自动将访问者重定向到站点的HTTPS版本:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

如果你有一个现有的。htaccess文件:

不要重复“重写引擎”。

确保以RewriteCond和RewriteRule开头的行立即跟随已经存在的RewriteEngine On。

在.htaccess文件中添加以下代码:

Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]

其中[您的域名]是您网站的域名。

你也可以重定向特定的文件夹从你的域名通过替换上面的最后一行代码:

RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]

Apache文档不建议使用重写:

要重定向http url到https,请执行以下操作: < VirtualHost *: 80 > ServerName www.example.com 重定向/ https://www.example.com/ < /虚拟主机> < VirtualHost *: 443 > ServerName www.example.com #……SSL配置在这里 < /虚拟主机>

这段代码应该放在主服务器配置文件中,而不是像问题中要求的那样放在.htaccess中。

这篇文章可能是在问题被提出和回答之后才出现的,但似乎是目前的做法。

根据GoDaddy.com,这是使用.htaccess将HTTP重定向到HTTPS的正确方法。第一行代码是自解释的。第二行代码检查HTTPS是否关闭,如果关闭,则通过运行第三行代码将HTTP重定向到HTTPS,否则将忽略第三行代码。

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

https://www.godaddy.com/help/redirect-http-to-https-automatically-8828