.htaccess 不将网站重定向到 https

.htaccess not redirecting web site to https

我在 Centos 6.6 上 运行 Apache/2.2.15,并且正在使用来自 StartCom 的免费证书。我的主页文件是 /var/www/index.php 所以我创建了一个包含以下内容的文件 /var/www/.htaccess,建议 here.

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/ [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context

但是,进入

myWebSite.com

在 URL 框中以 http 协议打开我的站点。如果我输入

https://myWebSite.com

相反,我使用 https 协议获取我的网站。我的目标是通过简单地输入

让我的网站使用 https 协议
myWebSite.com

我不明白为什么 .htaccess 文件没有影响。

您的 .htaccess 文件似乎没有被读取。因此,请确保您的配置中有 AllowOverride All

另外,对于您的规则,我不会使用 SERVER_NAME,它并不总是正确的,有时也不正确。我会使用 HTTP_HOST 变量或您的实际域名。您还应该为重定向指定 301,因为没有它 302 是默认值。您希望这是永久重定向。

RewriteEngine On
# This will enable the Rewrite capabilities
RewriteCond %{HTTPS} !^on [OR]
# This checks to make sure the connection is not already HTTPS
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^/?(.*)$ https://example.com/ [R=301,L]

我还把它放在了删除 www 的地方,因为你没有显示你正在使用它。