【问题标题】:Redirect to same path on new domain重定向到新域上的相同路径
【发布时间】:2011-08-16 20:22:17
【问题描述】:

您好,我有一个新域,想将我的用户重定向到新域的等效路径。

如果他们继续:oldsite.com/money.php?value=1

然后它应该引导他们到:newsite.com/money.php?value=1

我对所有页面都有相同的 header.php,所以这可以用一个简单的 php 行来完成吗?

【问题讨论】:

  • 你想用 php 脚本来做这件事吗?我不知道你的域在哪里,但你不能设置一些设置来为你做这件事吗?

标签: php apache redirect dns


【解决方案1】:

我会给你 2 个可能对其他事情有用的函数;

function currentURL() {
     $pageURL = 'http';
     ($_SERVER["SERVER_PORT"] === 443) ? $pageURL .= "s" : '';
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
      $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
     } else {
      $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     }
     return $pageURL;
 }


function redirect2NewDomain () {
    $url = currentURL();
    if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) === FALSE) {
       return false;
    }
    # Get the url parts
    $parts = parse_url($url);
    Header( "Location : {$parts['scheme']}://{$parts['host']}" );
}

当然,使用 .htaccess 更容易,对 SEO 也更好;

RewriteEngine on
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L] 

希望对你有帮助

【讨论】:

  • 我肯定会使用 .htaccess 方法。
  • 您可以在 PHP 脚本中发送 301 标头,从 SEO 角度来看,它会产生类似的效果。
  • 是的,我可以补充一点,它仍然不比 .htaccess 更好
  • 刚刚发现这篇文章,因为我遇到了同样的问题,使用 .htaccess 方法。效果很好!
  • 非常感谢您提供的信息 .htaccess
【解决方案2】:

您不应该在 PHP 中这样做。这些事情可以在您的 .htaccess 中轻松完成:

#Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.olddomain.com$[OR]
RewriteCond %{HTTP_HOST} ^olddomain.com$
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

此代码会将olddomain.com/page.php 重定向到newdomain.com/page.php

它还会重定向文件夹:olddomain.com/folder/newdomain.com/folder/

通过使用此代码,谷歌还将了解您正在切换域,并且不会因双重内容而降低您的页面排名。

【讨论】:

    【解决方案3】:

    这样的事情应该可以工作:

    $uri = $_SERVER['REQUEST_URI'];
    Header( "HTTP/1.1 301 Moved Permanently" );
    Header( "Location: http://newsite.com$uri" ); 
    

    但如果您可以修改您的网络服务器的配置,那将是一个更好的地方。

    【讨论】:

    • script_name 不包含获取变量
    【解决方案4】:

    我喜欢使用这个代码:

    // BEGIN redirect domain
    $domainRedirect = 'myNewDomain.com';
    if(
    ($_SERVER['HTTP_HOST'] != $domainRedirect)
    ){
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://".$domainRedirect.$_SERVER['REQUEST_URI']);
    exit;
    }
    // END redirect domain
    

    这个:

    header("HTTP/1.1 301 Moved Permanently"); 
    

    是可选的,但更适合 SEO:(https://moz.com/learn/seo/redirection)

    【讨论】:

      【解决方案5】:

      你可以用这个:

      $new_domain = "http://example.com"; //your new domain
      $uri = $_SERVER['REQUEST_URI']; // URL from the request with the get variables
      header("Location: " . $new_domain . $uri);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-07
        • 1970-01-01
        • 2023-03-08
        • 2014-09-12
        • 2019-07-16
        • 2012-01-01
        相关资源
        最近更新 更多