How do I detect, remove, and redirect urls with a

2019-07-20 21:05发布

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);
}

*Correction - I said at the end in the Title, and I mean the end, my code here apparantly detects for the pound sign anywhere in the url. *

标签: php url redirect
2条回答
女痞
2楼-- · 2019-07-20 21:52

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.

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.

查看更多
对你真心纯属浪费
3楼-- · 2019-07-20 21:56

You could use javascript to override the click event on all the tags on your page. If you're using jQuery you could do something like the following.

$(function() {
  $('a').click(function(ev) {
    alert(ev.currentTarget.hash);
    return false;
  });
});

<table>
<tr><td><a href='http://google.com/#test1'>Test 1</a></td></tr>
<tr><td><a href='/game/?p=test#test2'>Test 2</a></td></tr>
<tr><td><a href='#test3'>Test 3</a></td></tr>
</table>

When the link is clicked the click event is fired and at that point you can decide what to do based on the hash from the href. You could rebuild the href with the hash as a GET parameter and redirect the page or you could do turn it into an ajax call.

In the click event you could decide what to do with the hash tag. If you really need it on the server side then you could always append it to the query string or you could do an ajax call.

查看更多
登录 后发表回答