home » 编程开发 » PHP相关 » 利用wordpress主题的404.php来做301重定向

如果里换了网站URL结构最好的方法就是做301重定向,我以前讲过用.htaccess文件来做的,

如果你不会写.htaccess规则但是你懂一点PHP编程的话也是可以实现的,

把你的404.php写成下面这样的形式:

<?php
$info = $_SERVER['REQUEST_URI'];
if (strpos($info, '/author')) {  //返回字符串在另一个字符串中第一次出现的位置
	header("HTTP/1.1 301 Moved Permanently");
	$tmp = substr($info, 7);
	header("Location: http://$_SERVER[HTTP_HOST]/archives/author".$tmp);
} else if (strpos($info, '/date')) {
	header("HTTP/1.1 301 Moved Permanently");
	$tmp = substr ($info, 5);
	header("Location: http://$_SERVER[HTTP_HOST]/archives/date".$tmp);
} else if (strpos($info, '/category')) {
	header("HTTP/1.1 301 Moved Permanently");
	$tmp = substr ($info, 9);
	header("Location: http://$_SERVER[HTTP_HOST]/archives/category".$tmp);
} else if (strpos($info, '/tag')) {
	header("HTTP/1.1 301 Moved Permanently");
	$tmp = substr ($info, 4);
	header("Location: http://$_SERVER[HTTP_HOST]/archives/tag".$tmp);
}else if (strpos($info, '.html')) {
	header("HTTP/1.1 301 Moved Permanently");
	//pathinfo(path,options) 以数组的形式返回文件路径的信息
	//explode(separator,string,limit) 把字符串分割为数组
	//krsort() 对数组按照键名逆向排序
	//current() 返回数组中的当前元素
	$array = explode('-', pathinfo($info, PATHINFO_FILENAME));
	$i = count($array)-1;
	$tmp = $array[$i];
	header("Location: http://$_SERVER[HTTP_HOST]/archives/".$tmp);
}
else {
?>
[404页面内容]
<?php } ?>

当然我给出的只是一个演示,并不一定适合你的URL结构,你可以参考参考。

Tags: 标签:, ,
本博客所有文章如果没加特殊说明均为原创,如需转载引用请注明出处
[重阳博客:http://www.99xunle.com/archives/801]
随机文章 相关文章

One Response to “利用wordpress主题的404.php来做301重定向”

  1. 重阳  2010-03-24 16:31 says: 

    以上的代码等同于到这样的.htaccess

    Redirect permanent /author /archives/author
    Redirect permanent /date /archives/date
    Redirect permanent /category /archives/category
    Redirect permanent /tag /archives/tag
    RedirectMatch 301 ^/(.+)-(\d+)\.html$ /archives/$2

    Reply

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>