说起网站的301重定向,你一定也了解过它的作用吧,大家都知道在mod_rewrite模式下是可以新建.htaccess文件来做的,如以下为一个不带WWW的xysanying.cn重定向到的例子代码:http://www.xysanying.cn
RewriteEngine On
RewriteCond %{HTTP_HOST} ^studstu.com [NC]
RewriteRule ^(.*)$ http://www.studstu.com/$1 [L,R=301]
但很多主机用的是WIN系统的,而且还是虚拟主机,无法设置IIS来做301重定向,那么则多用代码来实现,比如网上很多的ASP、PHP、.NET等301重定向代码。
ASP代码:
<%
Response.Status='301 Moved Permanently'
Response.AddHeader 'Location','http://www.studstu.com'
Response.End
%>
PHP代码:
<? Header( 'HTTP/1.1 301 Moved Permanently' );
Header( 'Location: http://www.studstu.com' );?>
上面这种代码只适用于网站域名更换的情况下,即不同的域名和不同的空间根目录,把上面代码放置于旧站网站文件的顶部即可,这时访问旧站时就会重定向到新站http://www.xysanying.cn。如果网站是属于一个网站空间绑定2个域名,2个域名的根目录为同一个时,那么就会出现死循环了。
如果是一个网站绑定多个域名情况,将不带WWW的子域名或其他域名重定向到一个主域名,那么只需要加个判断:
ASP重定向代码:
<%
if request.ServerVariables('HTTP_HOST')='studstu.com' then
Response.Status='301 Moved Permanently'
Response.AddHeader 'Location','http://www.studstu.com'
Response.End
end if
%>
PHP重定向代码:
<?php
$the_host = $_SERVER['HTTP_HOST'];//取得进入所输入的域名
$request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';//判断地址后面部分
if($the_host !== 'studstu.com')//旧域名或子域名地址
{
header('HTTP/1.1 301 Moved Permanently');//发出301头部
header('Location: http://www.studstu.com'.$request_uri);//跳转到我的新域名地址
}
?>

