【发布时间】:2014-03-30 22:31:12
【问题描述】:
我在这方面完全是新手。我想 301 将 Wordpress 网站重定向到新域。我应该将重定向代码添加到哪个.php 文件?我在想可能是index.php?
【问题讨论】:
-
最好将重写规则应用于 .htaccess 文件。
-
我专门询问了 PHP 重定向。
标签: php redirect http-status-code-301
我在这方面完全是新手。我想 301 将 Wordpress 网站重定向到新域。我应该将重定向代码添加到哪个.php 文件?我在想可能是index.php?
【问题讨论】:
标签: php redirect http-status-code-301
如果你真的想从 php 重定向它,那么在 index.php 中这样做:
<?php
header('Location: http://www.example.com');
?>
但是,正如 Rahil Wazir 所建议的,您应该考虑在 Apache 级别进行。
【讨论】:
您可以手动发送 301 标头及其移动到的位置。
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.example.org/");
?>
【讨论】:
header("Location: http://someother.domain/place", true, 301); exit();
...说 “替换所有以前的相似标头 (true) 并使用永久重定向 (301) 的状态代码重定向到 http://someother.domain/place” - 这是纯粹的 - PHP "header" 方式...
如果你想走 WordPress 的路,你可以使用wp_redirect( $location, $status );
wp_redirect( 'http://someother.domain/place', 301 ); exit();
...基本上做同样的事情(+一些过滤器+清理位置)...
exit();!...否则它可能不起作用:-)(尤其是wp_redirect(...))
index.php 绝对是 错误 的地方 - 它可以被任何更新取代...
正确的位置和方法是将动作挂钩/添加到名为 template_redirectpre_get_posts 的动作中,
编辑:我发现template_redirect 有时太晚了,因为 有时 WordPress 会在该操作之前重写 URL 本身 - WordPress尝试“猜测”目标 url,如果请求的 url 与现有的 url 相似... - 您应该决定是否需要此功能并相应地选择操作...
...如果您不想要该功能,最好使用pre_get_posts,
这基本上意味着“尽快”
您可以将代码放入主题的 functions.php 文件中...
add_action('pre_get_posts', function(){
//do the redirect here
});
虽然template_redirect 动作只针对前端-end,
pre_get_posts 应该同时用于 - front&&back-end :-)
PS:您可能希望在更具体的阶段触发重定向:
只需搜索合适的 WordPress Action。
【讨论】: