Last Updated on February 25, 2022 by Amit
I often see users struggling with their RewriteRule to redirect fragment URLs.
Fragment is something that the server doesn’t receive meaning that a URL containing #path can not be redirected using htaccess or any other server side redirection methods.
Fragment usually appers at the end of the URL and starts with a “#” character.
Anything that comes after # in URL is part of URL fragment.
A fregment is handled client side ( by web browser) and used as jump to navigation link in a web page.
When a fragment URL is typed in browser address bar your web browser makes it so that the page automatically scrolls to the fragment href section on the requested page .
The following is an example of fragment URL:
In the above URL , /file.php is URL path and #foobar is a fragment.
Your web server only receives the URL path as request header string and the remaining part (#foobar) is trimmed or not sent. Since the fragment is manipulated client side , your webserver doesn’t get such URL segment and there is no way to handle it server side.
Redirect to a Fragment URL using RewriteRule
It is quite possible to redirect your original URL path to a fragment URL . For example example.com/thispath can be redirected to example.com/#thispath using NE and R (NoEscape and Redirect) flags in RewriteRule directive.
example.com/#thispath can not be redirected to example.com/thispath because the requested URL contains # path and its is not manipulated server-side.
You can’t redirect fragment using htaccess RewriteRule
RewriteRule ^path/#foobar /newpathWithoutFregment [R]
The rule above will never work because of the following two reasons :
- # is a special character in mod-rewite as it is used to add comments in RewriteRule.
- # is a fragment which is maintained by browser and its not sent to the server.
The rewiteRule above won’t work even if you escape the # character as its not even sent to the server.
The following Rewriterule works perfectly fine
You can redirect your URL path to fragment using NE and R flag.
Here is a RewriteRule example to redirect /foobar to /#foobar :
RewriteRule ^foobar /#foobar [NE,R]
The above example works because here you are redirecting your NonFregmentPath to a FragmentPath. You type the path /foobar into your browser, your browser then sends the path to server , server receives the path , reads htaccess rules and then issues a Redirect (/foobar => /#foobar) to your webbrowser . And finally your web browser makes the hash redirection.
The NE flag is important in the rule above. Without NE the # gets encoded to its hex value which may end up in an incorrect or not found path.
The window.location.hash() property returns the current page hash ie #foobar in this example.
You can learn more about JS location pproperties on the official Mozilla site here .
I hope the post was helpful. Thank you so much for reading.