.htaccess redirect anchor page/page#anchor to url

2019-03-01 01:07发布

问题:

How do I redirect page/page#anchor to http://www.example.com/page/page.

I tried the following code, but it's not working

RewriteRule ^page/page#anchor http://www.example.com/page/page [NE,L]

Could you please help me?

Peter

回答1:

That can't be done on server side since URI component after # is handled by client side only.

You can alternatively use this Javascript code to do the same:

<script>
if (location.href.indexOf("#") > -1) {
   location.assign(location.href.replace(/(page\/page)#anchor/i, "$1"));
}
</script>


回答2:

I believe the data after # is considered a fragment. Fragment data is not sent to the server. Therefore you cannot capture it using modrewrite.

the NE flag may let you capture ^/page/page and redirect to http://www.example.com/page/page#anchor but it won't work the other way around.

A simple JavaScript replace will replace the links and allow the users to click on them. But that won't help you with SEO if that is your ultimate goal.