如何在 PHP 中检测、删除和重定向带有 # 结尾的 url? [英] How do I detect, remove, and redirect urls with a # at the end in PHP?

查看:33
本文介绍了如何在 PHP 中检测、删除和重定向带有 # 结尾的 url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户要求我自动将任何带有井号的 url 重定向到没有井号的版本,但我认为我没有使用此公式在我的任何 url 中检测到 #.我使用 curPageURL() 公式通过电子邮件向自己发送了一个示例 URL,它不包含我正在测试的 URL 中的尾随 # 符号.

Client asked me to automatically redirect any urls with a pound sign in them to a version without a pound sign, but I don't think I am detecting a # in any of my urls with this formula. I emailed myself a sample URL using the curPageURL() formula and it didn't contain the trailing # sign in the url I was testing.

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$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;
}

if(stripos($currenturl,'#'))
{
    Header( "HTTP/1.1 301 Moved Permanently" ); 
    $location = 'Location: ' . str_replace('#','',$currenturl) . '/';
    Header($location);
}

*更正 - 我在标题的最后说,我的意思是最后,我的代码在这里明显地检测到 url 中任何地方的磅符号.*

推荐答案

# 后面的部分是散列"或片段".它完全是客户端 - 它永远不会发送到服务器(如果是,则会导致错误).因此,您的 PHP 脚本永远不会看到它,因此无法修复它.这是正确的行为,也是设计使然.

The part after the # is a "hash" or "fragment". It is entirely client-side - it is never sent to the server (and if it is, it results in an error). As such, your PHP script will never see it, and can't therefore fix it. This is correct behavior, and by design.

也就是说,您可以使用客户端解决方案(例如在带有 document.location.hash 的 JS 中)检查 #fragment 并从那里重定向.

That said, you could check for the #fragment using a client-side solution (e.g. in JS with document.location.hash) and redirect from there.

这篇关于如何在 PHP 中检测、删除和重定向带有 # 结尾的 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆