更改我所有的网站链接:什么是最好的方法


Changing all my website links: what is the best way?

可能重复:
.htaccess重写以将根URL重定向到子目录

我需要更改我网站上的所有链接(2455(。

当访问者来自谷歌(使用旧链接(时会出现问题,因为页面将是404 page not found

我想将旧链接重定向到页面的新版本。例如:

旧链接:

http://example.com/hotel/13234
http://example.com/hotel/132
http://example.com/hotel/323
http://example.com/page/about_us
http://example.com/page/contact

新链接:(添加"博客"(后的领域

http://example.com/blog/hotel/13234
http://example.com/blog/hotel/132
http://example.com/blog/page/about_us
http://example.com/blog/hotel/323
...
...
...

最好的方法是什么?

使用mod_rewrite:

RewriteEngine On
RewriteRule $ /blog [L,R=301]

这将用blog作为所有链接的前缀,并永久重定向它们。

您可以使用将它们重定向到新的Location

header('Location: /blog' . $_SERVER['PHP_SELF']);

如果你使用PHP版本>=5.4.0,你也可以用发送一个正确的HTTP状态代码301(永久移动(

http_response_code(301);

当您想要使用.htaccess时,可以使用RewriteCondRewriteRule进行重定向。

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/blog/
RewriteRule .* /blog$0 [L,R=301]

RewriteCond指令阻止重写已经以/blog开头的URL。否则,您将得到一个无休止的递归。RewriteRule指令在所有URL前面加上/blog,不应用进一步的规则L,并发送HTTP状态代码301 R=301

要使其工作,必须在.htaccess中允许这些指令。您可以在主conf文件或虚拟主机上下文中使用相同的指令。

相关文章: