Home > php教程 > php手册 > body text

php实现301永久重定向和302临时重定向方法

WBOY
Release: 2016-05-25 16:44:50
Original
2904 people have browsed it

在服务器中301与302对于搜索引擎来讲一个是永久的跳新的地址了,一个是告诉你暂时到了一个新地址了,那么我们在php中怎么实现301永久重定向和302临时重定向呢,下面我们一起来看看方法的实现程序.

实现重定向的原理很简单,就是Web服务器返回个HTTP header给浏访问者,PHP发送HTTP header这个功能是由header()函数来实现的,301,302,404 这些状态码是在HTTP协议中约定好的,所以不用打破沙锅问"为什么是301而不是3001”,扯多了,回到正题.

PHP 301重定向,代码如下:

header('HTTP/1.1 301 Moved Permanently'); 
Header( "Location: http://www.phprm.com/" );  
exit();
Copy after login

//或者如下代码

<?php 
//301永久重定向 
$http_protocol = $_SERVER[&#39;SERVER_PROTOCOL&#39;];   //http协议版本 
//如果是其他协议,则默认为HTTP/1.0 
if ( &#39;HTTP/1.1&#39; != $http_protocol && &#39;HTTP/1.0&#39; != $http_protocol )
$http_protocol = &#39;HTTP/1.0&#39;; 
//响应301状态码 
header("$http_protocol 301 Moved Permanently"); 
//指定重定向的URL 
$new_url = &#39;http://www.phprm.com/&#39;; 
header("Location:$new_url"); 
?>
Copy after login

PHP 302重定向,代码如下:

header("Location: http://www.phprm.com/");  
exit();
Copy after login

顺到把PHP 404错误也附带上,代码如下:

header("HTTP/1.1 404 Not Found"); 
exit();
Copy after login

这里关于php 301与302重定向就讲到了这里了,下面附一下apache做法,例:

APACHE代码如下:

Redirect 301 /old/old.htm http://www.phprm.com/new.htm 
Redirect permanent /one http://phprm.com/two 
RedirectMatch 301 (.*).gif$ http://www.phprm.com/images/$1.jpg
Copy after login

使用mod_rewrite重写URL方式

APACHE代码如下:

Options +FollowSymLinks 
RewriteEngine on 
RewriteCond %{HTTP_HOST} ^phprm.com 
RewriteRule ^(.*)$ http://www.phprm.com/$1 [R=permanent,L]
Copy after login

关于apache htaccess这里就不介绍人了与mod_rewrite重写URL方式几乎是完全一样.


永久地址:

转载随意~请带上教程地址吧^^

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!