Thursday, November 7, 2024

Apache用.htaccess来实现强制https访问

我们可以用Apache的.htaccess的重定向规则来实现http强制跳转到https访问网站。

重要提示:必须将代码放到.htaccess文件内容的最前面,以保证重定向优先权。

代码如下:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domain.com/$1 [R,L]

或者

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]

或者

RewriteEngine on
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

如果是在子目录,可以用

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} subfolder
RewriteRule ^(.*)$ https://www.domain.com/subfolder [R,L]

将以上代码复制到.htaccess中即可。

2 comments

  1. 我的图片域名image.yuhaitao.com也配置了一个ssl证书,如何将之前的图片链接都转换为https://image.yuhaito.com?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.