基于具有ServerName的条件的Apache 2重定向

时间:2016-04-01 10:48:16

标签: apache redirect mod-rewrite

我有一个www.domain.com的虚拟主机,它将所有内容重定向到https

<VirtualHost *:80>
ServerName www.domain.com
ServerAlias domain.com *.domain.com

RewriteEngine on
RewriteCond %{SERVER_NAME} =*.domain.com [OR]
RewriteCond %{SERVER_NAME} =www.domain.com [OR]
RewriteCond %{SERVER_NAME} =domain.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</VirtualHost>

这将重定向来自

的所有请求
  • domain.comhttps://domain.com
  • www.domain.comhttps://www.domain.com
  • *.domain.comhttps://*.domain.com

但我想在www上强制执行domain.com

我试过了:

RewriteEngine on
RewriteCond %{SERVER_NAME} =*.domain.com [OR]
RewriteCond %{SERVER_NAME} =www.domain.com [OR]
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
RewriteCond %{SERVER_NAME} =domain.com
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]

但这不起作用..

有人可以帮助他们实现这一目标,而无需为VirtualHost创建另一个domain.com

1 个答案:

答案 0 :(得分:0)

<VirtualHost *:80>
ServerName www.domain.com
ServerAlias domain.com *.domain.com

RewriteEngine On

RewriteCond %{HTTP_HOST} =domain.com [OR]
RewriteCond %{HTTP_HOST} =www.domain.com 
RewriteRule ^/(.*)$ https://www.domain.com/$1

RewriteCond %{HTTP_HOST} !=domain.com
RewriteCond %{HTTP_HOST} !=www.domain.com  
RewriteRule ^/(.*)$ https://%{HTTP_HOST}/$1
</VirtualHost>

第一个重写规则会将http://domain.comhttp://www.domain.com的所有请求重定向到https://www.domain.com

第二个重写规则会将所有请求从http://*.domain.com重定向到https://*.domain.com