我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
除非你需要mod_rewrite做其他事情,使用Apache核心IF指令更干净更快:
<If "%{HTTPS} == 'off'">
Redirect permanent / https://yoursite.com/
</If>
你可以在IF指令中添加更多的条件,比如确保一个没有www前缀的规范域:
<If "req('Host') != 'myonetruesite.com' || %{HTTPS} == 'off'">
Redirect permanent / https://myonetruesite.com/
</If>
使用mod_rewrite做任何事情都有很多熟悉的惯性,但看看这是否适合你。
更多信息:https://httpd.apache.org/docs/2.4/mod/core.html#if
要看到它的行动(尝试没有www。或https://,或用。net代替。com): https://nohodental.com/(我正在做的一个网站)。
其他回答
根据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
如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
我尝试了所有我能在互联网上找到的。htaccess配置,但没有一个有效。 然后,我意识到Apache不鼓励使用mod_rewrite。
我的解决方案是在以下文件夹下编辑apache配置文件: /etc/apache2/sites-enabled
您将有一个名为000-default.conf的强制文件和一个名为000-default-le-ssl.conf的ssl配置文件(如果您从letsencrypt/certbot安装了ssl证书)。但是,这些文件的名称可能不同,这取决于您在设置网站时提供的文件名。
在000-default.conf中,我在<VirtualHost *:80>中编辑了以下内容:
<VirtualHost *:80>
ServerName example.com
Redirect / https://example.com/
</VirtualHost>
在000-default-le-ssl.conf中,我在<VirtualHost *:80>中编辑了以下内容:
<VirtualHost *:80>
ServerName example.com
Redirect / https://example.com/
</VirtualHost>
不需要其他重定向。
保存文件,然后使用sudo service apache2 restart重启apache服务器
我发现最好的方式https和www域名是
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
经过多次尝试,考虑没有www和有www,这是可行的
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (www\.)?yourdomain.com
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]