【问题标题】:Redirect 301 relative to url in php在php中相对于url重定向301
【发布时间】:2013-02-28 17:17:16
【问题描述】:

我要迁移到一个新域名,我需要将所有传入链接重定向到新域名。所有页面都在两个网站上。

(例如:www.oldsite.com/services.php 和 www.exemple.com/services.php 都是活动的并且相同。)

我想知道我的代码是否对 SEO 友好而不会弄乱 .htaccess 文件。

<?php
$referer = $_SERVER['SERVER_NAME'];
$domain = "www.exemple.ca";
$uri = $_SERVER['REQUEST_URI'];

if(strpos($referer,$domain) === false) {
    header( "HTTP/1.1 301 Moved Permanently" );
    header( "Status: 301 Moved Permanently" );
    header( "Location: http://www.exemple.ca$uri" );
    exit(0);
} ?>

【问题讨论】:

  • 通过 htaccess 来做会容易得多(两行)

标签: php redirect seo


【解决方案1】:

几点:

  • 您可能需要HTTP_HOST(请求的主机名),而不是SERVER_NAME
  • 假设您没有使用任何子域,则无需使用strpos,我只需比较两个主机名并在它们不相等时重定向
  • 您只需要一个 301 标头
  • htaccess 会比使用 PHP 快得多,特别是如果您已经有一个 htaccess 文件

考虑到这一点,我可能会将您的代码重写为:

<?php
$referer = $_SERVER['HTTP_HOST'];
$domain = "www.exemple.com";
$uri = $_SERVER['REQUEST_URI'];

if($referer != $domain) {
    header( "Location: http://www.exemple.ca$uri" true, 301);
    exit(0);
} ?>

您也可能只想对 GET 请求执行此操作。

htaccess 版本(假设 mod_rewrite 已启用)将是:

RewriteEngine On

RewriteCond %{HTTP_HOST} !(^www.exemple.ca)
RewriteRule (.*) http://www.exemple.ca/$1 [R=301,L]

【讨论】:

  • 非常感谢这些提示
【解决方案2】:

301 与 SEO 一样友好。它向蜘蛛表明该页面已永久移动。

【讨论】:

    猜你喜欢
    • 2014-10-26
    • 2021-04-01
    • 2017-12-30
    • 2015-12-30
    • 2012-10-28
    • 2012-12-19
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多