通过.htaccess将http转换为https

77
我已经查看了现有的问题,但是没有找到适合我的答案。
我目前正在运行一个具有安全SSL证书的站点。它可以在https://www.example.co.uk访问,但问题是该站点也可以在http://www.example.co.uk访问 - 我不希望这种情况发生。我需要将其从http重定向到https。
我找到了这个代码片段,可以在.htaccess文件中使用。
Options +FollowSymLinks 
RewriteEngine on 
RewriteCond %{HTTP_HOST} ^example.co.uk [NC] 
RewriteRule ^(.*)$ https://example.co.uk/$1 [L,R=301]

当用户在地址栏输入example.co.uk时,这个方法可以正常工作,但我还需要添加一个条件语句,以便如果用户输入'www.example.co.uk'或'http://www.example.co.uk'时也能正常工作。我尝试过使用[OR]等方法,但这会导致服务器错误。感谢任何帮助和建议。祝好。

17个回答

201

尝试以下方法:

 RewriteEngine On
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

另外,你也可以根据端口号进行重定向,例如:

 RewriteCond %{SERVER_PORT} ^80$
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

这将把所有在80端口接收的请求重定向到HTTPS。


17

5

5

试试这个,我用过它,效果非常好

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

4

3
我尝试了以上所有代码,但是没有一个代码适用于我的网站。然后我尝试了这个代码,这个代码在我的网站上运行得非常好。您可以在htaccess中使用以下规则:
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

//Redirect http to https
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

//Redirect non-www to www
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

</IfModule>

请用您的域名替换example.com,抱歉我的英语不好。

2
# Switch rewrite engine off in case this was installed under HostPay.
RewriteEngine Off

SetEnv DEFAULT_PHP_VERSION 7

DirectoryIndex index.cgi index.php

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# RewriteCond %{HTTP_HOST} ^compasscommunity.co.uk\.com$ [NC]
# RewriteRule ^(.*)$ https://www.compasscommunity.co.uk/$1 [L,R=301]

1

如果您想在AWS Beanstalk上添加http到https重定向,由于这是搜索结果中的顶部之一,所以接受的解决方案将不起作用。您需要使用以下代码:

RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^.*$ https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

1

如果您想将HTTP重定向到HTTPS并希望在每个URL中添加www,请使用以下htaccess

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

它将先将HTTP重定向到HTTPS,然后再重定向到www。

1
完美的代码进入HTML索引:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^YourNameWebsite\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.YourNameWebsite\.com$
RewriteRule ^/?$ "https\:\/\/YourNameWebsite\.com\/index\.html" [R=301,L]


完美的代码进入 PHP 索引页:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^YourNameWebsite\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.YourNameWebsite\.com$
RewriteRule ^/?$ "https\:\/\/YourNameWebsite\.com\/index\.php" [R=301,L]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接