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

时间:2012-12-28 18:10:56

标签: php .htaccess hyperlink

  

可能重复:
  .htaccess rewrite to redirect root URL to subdirectory

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

当访问者来自Google(使用旧链接)时会出现问题,因为该页面将为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

...
...
...

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:5)

使用mod_rewrite

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

这会将所有链接加上blog作为前缀,并永久重定向。

答案 1 :(得分:2)

您可以使用

将它们重定向到新的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开头的网址。否则你将获得无休止的递归。 RewriteRule指令使用/blog作为所有网址的前缀,不再应用其他规则L,并发送HTTP状态代码301 R=301

为了实现这一点,必须在.htaccess中允许这些指令。您可以在主conf文件或虚拟主机上下文中使用相同的指令。

相关问题