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

  

443,Apache,Apache 80 强制 443,Apache https,Apache rewrite rule,apache 带www,https,rewrite,SSL,www,三种,使用,及强,域名,开头,强制,方法,正确,种方,端口,设置,访问,通过,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]

  •   正在提交中,请稍候...
      评论提交成功
    回复 的评论,点击取消回复

    账号密码登录