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

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

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

ServerName mysite.example.com
DocumentRoot /usr/local/apache2/htdocs
Redirect permanent /secure https://mysite.example.com/secure


ServerName mysite.example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
# etc...

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

ServerName www.example.com
Redirect permanent / https://secure.example.com/


ServerName secure.example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
# etc...

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

Redirect permanent "https://%{HTTP_HOST}/"

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

Redirect /login https://mysite.example.com/login
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模块支持
方式一
[cc]RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L][/cc]
方式二
[cc]
ServerName example.com
Redirect permanent / http://www.example.com/
[/cc]
方式三、同时将http重定向到https且将www重定向到不带www的顶级域名
[cc]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][/cc]
如果是将不带www的顶级域名重定向到带www的域名,只需要修改最后一行
[cc]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][/cc]

Leave a Comment