How to Detect and Redirect from URL with Anchor Us

2019-06-27 22:42发布

问题:

I've seen a number of examples of the opposite, but I'm looking to go from an anchor/hash URL to a non-anchor URL, like so:

From: http://old.swfaddress-site.com/#/page/name
To:   http://new.html-site.com/page/name

None of the examples at http://karoshiethos.com/2008/07/25/handling-urlencoded-swfaddress-links-with-mod_rewrite/ have functioned for me. It sounds like REQUEST_URI has the /#/stuff in it, but neither me nor my Apache (2.0.54) see it.

Any ideas, past experiences or successes?

回答1:

Anything after the # is a fragment, and will not be sent to the webserver. You cannot capture it at any point there, you'll have to use a client-sided approach to capture those.



回答2:

@RobRuchte : would it not be better to use window.location.hash, with a replace instead of a regular expression?

var redirectFragment = window.location.hash.replace(/^#/,'');
if ( '' !== redirectFragment ) {
    window.location = 'http://new.html-site.com' + redirectFragment;
}


回答3:

I'm the author of the post you linked to. Wrikken is correct, the content after the named anchor is not sent to the server unless something has mangled the URL along the way. On the client side, you need some JavaScript like this in your landing page to redirect the swfaddress links to corresponding URLs on another domain:

var re = new RegExp('#(.*)');
var redirectFragment = re.exec(document.location.toString());
if (redirectFragment!=null)
{
    document.location = 'http://new.html-site.com'+redirectFragment[1];
}


回答4:

I used a modified version of the answer by @m14t. This works for redirects that look like http://example.com/path/to/page#fragment --> http://example.com/path/to/page/fragment. Notice that I also concatenated the window.location.pathname for the redirect, otherwise I would not get the full path for the redirect. If the new file path is completely different from the old one, then this would not work.

var redirectFragment = window.location.hash.replace(/#/,'/');
if ( '' !== redirectFragment ) {
    window.location = 'http://example.com' + window.location.pathname + redirectFragment;
}

In my case, I needed to build fragmented links into individual pages, which is part of what is commonly done to improve a website's SEO.