LINUX,WINDOUS,PHP,ASP,.NET等,如何实现301重定向
设置301重定向(301转向,跳转)的实现方法也有很多,下面根据不同的空间服务器类型和程序语言列出各种301重定向实现代码,要参考的童靴请对号入座:
Linux 主机 Apache服务器 Mod-Rewrite 模式:通过.htaccess文件
当浏览器或搜索引擎spider发送一个页面请求时,Web服务器就会检查一个名为'.htaccess'的文件,这个文件指明了如何处理页面请求,通过修改设置'.htaccess'文件就可以告知搜索引擎某个页面是302转向(临时跳转)还是301重定向(永久性跳转)。有的Linux主机服务器还支持你在管理后台直接设置301转向。如果不能在后台设置,实现301重定向步骤也很简单:新建一个文件名为.htaccess.txt的文档(注意前面的点号不能遗漏),在txt文档中写入以下301转向代码:
1
|
Options +FollowSymLinks
|
2
|
RewriteEngine on
|
3
|
rewritecond %{http_host} ^nowamagic.net [nc]
|
4
|
rewriterule ^(.*)$ http: //www.nowamagic.net/$1 [r=301,nc]
|
或者
1
|
RewriteEngine On
|
2
|
RewriteCond %{HTTP_HOST} !^nowamagic.net$ [NC]
|
3
|
RewriteRule ^(.*)$ http: //www.nowamagic.net/$1 [L,R=301]
|
保存文件,将文件名称末尾的.txt去掉,上传到网站根目录即可。上面的代码表示整站所有的以带www的域名www.nowamagic.net为地址的网页都会301转向到不带www的域名nowamagic.net(不仅是首页,子目录/网页也可以)。如果是其他域名要重定向到 nowamagic.net 这个新域名,则在.htaccess文件中加入如下重定向代码:
1
|
Options +FollowSymLinks
|
2
|
RewriteEngine on
|
3
|
RewriteRule ^(.*)$ http: //www.nowamagic.net/$1 [L,R=301]
|
Windows主机IIS下的301转向设置
在IIS 管理后台 -> 选择你要重定向的文件或文件夹 -> 右键"重定向到URL" -> 输入需要转向的目标URL ->选择"资源的永久重定向"。
另外,如果你的Windows虚拟主机空间支持ISAPI_Rewrite,那么在IIS下利用ISAPI_Rewrite不仅可以实现url 重写,还可以用来设置301转向,下面分别是三个版本的ISAPI_Rewrite对应的带www的域名301转向到不带www域名的代码:
01
|
# ISAPI_Rewrite 1.3 版本 域名的301重定向
|
02
|
RewriteCond Host: ^www\.farlee\.info$
|
03
|
RewriteRule (.*) http\: //farlee\.info$1 [I,R]
|
04
|
|
05
|
# ISAPI_Rewrite 2.x 版本
|
06
|
RewriteCond Host: ^www\.farlee\.info$
|
07
|
RewriteRule (.*) http\: //farlee\.info$1 [I,RP]
|
08
|
|
09
|
# ISAPI_Rewrite 3.x 版本
|
10
|
RewriteCond %{HTTP:Host} ^www\.farlee\.info$
|
11
|
RewriteRule (.*) http\: //farlee\.info$1 [NC,R=301]
|
在其他情况下,如不同域名之间在IIS下的301重定向代码请看详细介绍:ISAPI Rewrite实现IIS 301转向。
PHP 301 重定向代码
301重定向也可以在php文件中通过加入php header来实现,代码如下:
1
|
<?php
|
2
|
header( "HTTP/1.1 301 Moved Permanently" );
|
3
|
header( "Location: http://nowamagic.net/newpage.html" );
|
4
|
exit ();
|
5
|
?>
|
ASP 301 重定向代码
1
|
<%@ Language=VBScript %>
|
2
|
<%
|
3
|
Response.Status= "301 Moved Permanently"
|
4
|
Response.AddHeader "Location" , http: //nowamagic.net
|
5
|
%>
|
ASP.NET 301 重定向代码
1
|
<script language= "c#" runat= "server" >
|
2
|
private void Page_Load( object sender, System.EventArgs e)
|
3
|
{
|
4
|
Response.Status = "301 Moved Permanently" ;
|
5
|
Response.AddHeader( "Location" ,http: //nowamagic.net);
|
6
|
}
|
7
|
</script>
|
CGI Perl下的301转向代码
1
|
$q = new CGI;
|
2
|
print $q ->redirect( "http://nowamagic.net" );
|
JSP下的301转向代码
1
|
<%
|
2
|
response.setStatus( 301 );
|
3
|
response.setHeader( "Location" , "http://nowamagic.net" );
|
4
|
response.setHeader( "Connection" , "close" );
|
5
|
%>
|