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

我用的是PHP。


当前回答

这将重定向所有的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]

其他回答

如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html

Not only can you do this in your .htaccess file, you should be doing this period. You will also want to follow the steps here to get your site listed on the HSTS preload list after you implement this redirect so that any requests to the insecure http version of your website never make it past the user agent. Instead, the user agent checks the requested URI against a baked in list of https only websites and, if the requested URI is on that list, changes the protocol from http to https before transmitting the request to the server. Therefore, the insecure request never makes it out into the wild and never hits the server. Eventually when the internet changes over to https only the HSTS preload list will not be needed. Until then, every site should be using it.

为了执行重定向,我们需要启用重写引擎,然后将所有流量从http端口80重定向到https。

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourwebsite.tld/$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]

我实际上试图让它在没有负载均衡器的EC2实例上工作,因为这需要花钱。我到处都读到。htaccess不是“正确”的方式。很明显,这是可行的,但我只是想按规矩办事。我按照所有示例更新httpd.conf文件,并添加了许多不必要的东西。事实证明,你真正需要的唯一一行是:

Redirect permanent / https://www.yourdomain.com

我的问题是,最初我已经在httpd.conf中的VirtualHost标签中添加了这个,这是很多帖子告诉你要做的,但它不起作用。原来有一个单独的conf文件存储在/etc/httpd/conf中。d调用yourdomain.conf,它已经有了VirtualHost标签,并且覆盖了我的httpd.conf设置。我只是添加了上面的行里面,瞧,它立即重定向到https。端口443不需要单独的VirtualHost。

它现在正在工作,VirtualHost标签看起来是这样的:

<VirtualHost *:80>
    ServerName yourdomain.com
    DocumentRoot /var/www/html
    ServerAlias www.yourdomain.com
    ErrorLog /var/www/error.log
    CustomLog /var/www/requests.log combined
    Redirect permanent / https://www.yourdomain.com
</VirtualHost>

注意:我已经从certbot(爱那些家伙)的免费证书设置了TLS,只是试图将常规http调用重定向到工作的https站点。

这将重定向所有的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]