主域名:www.test.com ,如何让辅助域名:www.daixuan.com 自动跳转到主域名?

Rewrite:301永久重定向,302临时重定向


前提是LAMP和Discuz论坛www.test.com可以通过本地访问,widnows的hosts文件添加:192.168.101.230 www.test.com www.daixuan.com www.daixuanlinux.com


1、修改虚拟主机配置文件

[root@daixuan ~]# vim /usr/local/apache2/conf/extra/httpd-vhosts.conf 添加红色的rewrite模块

<VirtualHost *:80>

#   ServerAdmin webmaster@dummy-host.example.com

    DocumentRoot "/data/www"

    ServerName www.test.com

    ServerAlias www.daixuan.com

#   ErrorLog "logs/dummy-host.example.com-error_log"

#   CustomLog "logs/dummy-host.example.com-access_log" common

   <IfModule mod_rewrite.c>

     RewriteEngine on                          Rewrite打开

     RewriteCond %{HTTP_HOST} ^www.daixuan.com$        条件:满足www.daixuan.com

     RewriteRule ^/(.*)$ http://www.test.com/$1 [R=301,L]  规则:跳转到www.test.com

   </IfModule>                               /(.*)$表示/任何内容

   <Directory /data/www/abc/>

   AllowOverride AuthConfig

   AuthName "Please input your name and password"

   AuthType Basic

   AuthUserFile /data/.htpasswd

   require valid-user

   </Directory>

</VirtualHost>


2、重启Apache

[root@daixuan ~]# apachectl restart


3、测试

浏览器打开:www.daixuan.com 自动跳转到www.test.com,说明跳转成功。

[root@daixuan ~]# curl -x 192.168.101.230:80 www.daixuan.com/123456789 -I

HTTP/1.1 301 Moved Permanently

Date: Tue, 01 Dec 2015 02:22:09 GMT

Server: Apache/2.2.31 (Unix) PHP/5.4.45

Location: http://www.test.com//123456789

Content-Type: text/html; charset=iso-8859-1


4、拓展如果希望www.123.com和www.daixuan.com都跳转到www.test.com,怎么修改配置文件?


如果需要PC机测试虚拟机的Discuz论坛,需要配置windows的hosts文件

192.168.101.230 www.test.com www.daixuan.com www.daixuanlinux.com  www.123.com


修改虚拟主机配置文件

[root@daixuan ~]# vim /usr/local/apache2/conf/extra/httpd-vhosts.conf 添加红色的rewrite模块

<VirtualHost *:80>

#   ServerAdmin webmaster@dummy-host.example.com

    DocumentRoot "/data/www"

    ServerName www.test.com

    ServerAlias www.daixuan.com

    ServerAlias www.123.com  设置/data/www目录的别名:www.123.com

#   ErrorLog "logs/dummy-host.example.com-error_log"

#   CustomLog "logs/dummy-host.example.com-access_log" common

   <IfModule mod_rewrite.c>

     RewriteEngine on

     RewriteCond %{HTTP_HOST} ^www.daixuan.com$ [OR]  OR代表访问daixuan.com或者123.com

     RewriteCond %{HTTP_HOST} ^www.123.com$

     RewriteRule ^/(.*)$ http://www.test.com/$1 [R=301,L]

   </IfModule>

   <Directory /data/www/abc/>

   AllowOverride AuthConfig

   AuthName "Please input your name and password"

   AuthType Basic

   AuthUserFile /data/.htpasswd

   require valid-user

   </Directory>

</VirtualHost>


注:Apache301跳转使用的是rewrite模块

[root@daixuan ~]# apachectl -M  

rewrite_module (shared) php