Apache设置http80端口强制使用443端口https的正确三种方法及强制www开头

1、通过虚拟主机配置文件(.conf文件)重定向(Redirect permanent 为永久重定向301)

1
2
3
4
5
6
7
8
9
10
11
12
13
NameVirtualHost *:80
<virtualHost *:80>
   ServerName mysite.example.com
   DocumentRoot /usr/local/apache2/htdocs
   Redirect permanent /secure https://mysite.example.com/secure
</virtualHost>

<virtualHost _default_:443>
   ServerName mysite.example.com
   DocumentRoot /usr/local/apache2/htdocs
   SSLEngine On
# etc...
</virtualHost>

如果定义任何请求均走https,可以省略为:

1
2
3
4
5
6
7
8
9
10
11
12
NameVirtualHost *:80
<virtualHost *:80>
   ServerName www.example.com
   Redirect permanent / https://secure.example.com/
</virtualHost>

<virtualHost _default_:443>
   ServerName secure.example.com
   DocumentRoot /usr/local/apache2/htdocs
   SSLEngine On
# etc...
</virtualHost>

2、通过主机header动态重定向

1
2
3
<location />
  Redirect permanent "https://%{HTTP_HOST}/"
</location>

3、通过.htaccess配置文件 注:采用.htaccess文件进行重定向需要apache开启mod_rewrite模块支持

1
 Redirect /login https://mysite.example.com/login
1
2
3
4
5
6
7
8
9
10
RewriteEngine On
# This will enable the Rewrite capabilities

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

RewriteRule ^/?secure/(.*) https://%{SERVER_NAME}/secure/$1 [R,L]
# This rule will redirect all users who are using any part of /secure/ to the same location but using HTTPS.
# i.e.  http://www.example.com/secure/ to https://www.example.com/secure/
# This means if you dont want to force HTTPS for all directories you can force it for a specific sub-section of the site.

4、将不含www的域名301到带www的二级域名 注:采用.htaccess文件进行重定向需要apache开启mod_rewrite模块支持
方式一

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

方式二

1
2
3
4
<virtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</virtualHost>

方式三、同时将http重定向到https且将www重定向到不带www的顶级域名

1
2
3
4
5
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

如果是将不带www的顶级域名重定向到带www的域名,只需要修改最后一行

1
2
3
4
5
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
原文链接:https://xiaohost.com/3832.html,转载请注明出处。
0

评论0

请先