Wednesday, March 22, 2017

Redirecting Hash(#) Fragments with Apache rewrite.

The character string beginning with a pound sign, # being interpreted as its HTML entity hex equivalent, %23..
It can led the url with 404 error.
It is very simple to redirect hash-fragment requests to proper destination using rewrite techniues.

You can find in the web access logs with HTML character code %23 for #.

Example1:

http://www.test.com/path/%23blog-123

To fix this you can do like this.

RewriteRule ^/(.*)%23blog-(.*)$ /$1#blog-$2 [R=301,L,NE]

In the given example  the first (.*) is used to replace the $1, and the second (.*) is used to replace the $2. The key here is the NE flag, which prevents # from being converted to its hex code of %23 during the rewrite.

Example2:

It is also easy to do general url redirection.
Let's assume you wanted to redirect url /web/tips-for-parents to /take-away-for-enablers/#familiestrack
RewriteRule  ^/web/tips-for-parents  /take-away-for-enablers/#familiestrack [R=301,L,NE]

Exaple3:

Lets redirect a part of the url which is appended as hash-fragment.
RewriteRule ^/path-of-url/(.*)/?$  /path-of-url/#$1 [R=301,L,NE]

So if request is for /path-of-url/newsite, it will redirected to /path-of-url/#newsite


NE|noescape : By default, special characters, such as & and ?, for example, will be converted to their hexcode equivalent. Using the [NE] flag prevents that from happening.

Apache flag NE