【问题标题】:Redirect only if url has certain value仅当 url 具有特定值时才重定向
【发布时间】:2018-12-29 20:43:47
【问题描述】:

所以我已将我的网站从 site.com 移至 sub.site.com。我还移动了预订系统。

我是否可以在 site.com 上的 index.php 上使用 PHP 代码来检查用户是否希望 site.com/unbook.php 自动将它们重定向到 sub.site.com/unbook.php

最佳做法是某种“如果 url 中有任何东西而不是 site.com,则重定向所有内容”

类似

$urlafter = explode("site.com", $url);
if (strlen ($urlafter[1]) > 0 ) {
    header("Location: sub.site.com".$urlafter[1]);
    exit();
}

或者使用$_SERVER[REQUEST_URI]甚至.htaccess之类的东西会更好

-- 编辑--

不重复,因为它们只显示 .htaccess 答案,我更喜欢 PHP

【问题讨论】:

标签: php redirect webserver url-redirection


【解决方案1】:

使用 Htacces 更适合场景。 在 site.com 的 .htaccess 文件中,您可以设置以下规则来重定向:

Redirect 301 / http://sub.site.com/

301 用于永久重定向。
如果重定向是临时的,您可以改用 302。

在 PHP 中你可以使用下面的代码来替换域:

$uri = $_SERVER['REQUEST_URI'];
$old_domain = 'yoursite.com';
$new_domain = 'sub.yoursite.com';

$old_domain_pos = strpos($url, $old_domain);

$redirect_url = substr($url, 0, $old_domain_pos).$new_domain.substr($url, ($old_domain_pos+strlen($old_domain)));

上面的代码只替换了域一次,其余的都保持原样。 如果您的 url 如下所示,其中域可能在查询字符串中重复,需要自行替换。

http://www.yoursite.com/get/?assset=www.yoursite.com/imgs/pic01.png

那么你可以考虑string_replace方法。

$redirect_url = str_replace($old_domain, $new_domain, $url);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    相关资源
    最近更新 更多