LAMP--域名 301 跳转
2017-10-25
LAMP--域名 301 跳转
一个站点可能会有多个域名,而多个域名总得有个主次,例:www.123.com (主),www.test.com (次)。希望实现不管用哪个域名访问,最终都跳到 www.123.com 上。这个行为叫域名跳转,这里的 301 只是个状态码,跳转除了 301 外还有 302。
[root@localhost ~]# vim /usr/local/apache2/conf/extra/httpd-vhosts.conf
在对应的虚拟主机配置文件中加入
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.test.com$
RewriteRule ^/(.*)$ http://www.123.com/$1 [R=301,L]
</IfModule>
如果是多个域名,可以这样设置:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.test.com [OR]
RewriteCond %{HTTP_HOST} ^www.test1.com$
RewriteRule ^/(.*)$ http://www.123.com/$1 [R=301,L]
</IfModule>
或者
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.123.com$
RewriteRule ^/(.*)$ http://www.123.com/$1 [R=301,L]
</IfModule>
重启 apache 后,在浏览器访问 www.test.com 会直接跳到 www.123.com 。使用 curl 命令测试一下。
[root@localhost ~]# curl www.test.com -I
HTTP/1.1 301 Moved Permanently
Date: Wed, 18 May 2016 01:46:04 GMT
Server: Apache/2.2.31 (Unix) PHP/5.6.10
Location: http://www.123.com/
Content-Type: text/html; charset=iso-8859-1