我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
我发现了一种方法,强制我的网站的所有页面从http重定向到https的模拟页面,为我工作。
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
其他回答
如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
这将重定向所有的url到https和www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
要将所有http请求重定向到https,您可以使用:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
如果mod-rewrite没有启用,并且你在apache 2.4上,你也可以在If指令中使用Redirect将http请求重定向到https。
Apache 2.4。
<if "%{HTTPS} !~ /on/">
Redirect / https://www.example.com/
</if>
这对我来说很管用:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
例如,http://server/foo?email=someone%40example.com可以正常重定向,没有任何问题。 文件.htaccess位于网站根文件夹(例如名为public_html)。 它是可以使用的 重写%{SERVER_PORT} !^443$ instead of重写%{HTTPS} !on
最佳解决方案取决于您的需求。这是对之前发布的答案的总结,并添加了一些上下文。
如果你使用Apache web服务器并且可以更改其配置,请参考Apache文档:
<VirtualHost *:80>
ServerName www.example.com
Redirect "/" "https://www.example.com/"
</VirtualHost>
<VirtualHost *:443>
ServerName www.example.com
# ... SSL configuration goes here
</VirtualHost>
但你还问是否可以在.htaccess文件中进行。在这种情况下,你可以使用Apache的RewriteEngine:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
如果一切正常,你想让浏览器记住这个重定向,你可以将最后一行更改为:
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
但如果你在这个方向上改变了主意,要小心。浏览器会记住它很长一段时间,不会检查它是否改变了。
根据web服务器配置,您可能不需要第一行RewriteEngine On。
如果你在寻找一个PHP解决方案,看看$_SERVER数组和header函数:
if (!$_SERVER['HTTPS']) {
header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
}