Last Updated on May 1, 2021 by Amit

Redirect URL fregments using htaccess

In this post I am going to give my answer with some code explainations to the following frequently asked question on internet :

“Is it possible to rewrite URI fregment using RewriteRule in htaccess?”

This is the question that is asked most often by newbies on StackOverflow .
Some mod_rewrite beginners often post these type of questions on stackoverflow with hope that someone experienced will provide them a working solution for this. But they are always suggested to use a client-side redirection method for this as the `#` isn’t sent to the server.
In this post I am not giving you a rewriteRule based solution as you know it’s not part of Server side redirection but I will explain why it can’t be used in internal RewriteRules .

What is a fregment in URL

URI fregment is part of URL that appears at the end.

A typical URL with fregment looks something like the following :
The #foobar in the URL above is a fregment.
URL fregments are maintained by browsers.
The # and anything after it in URL is not sent to the server.
So, if you type the above URL into your browser the server will only receive https://example.com/file.php while the fregment part remains on the browser.
The basic use of fregment in a URL is to provide “jump to page” section links. When the # is present in URL your browser decides what to do with it.

You can use RewriteRule to redirect your new URL to an external URL with fregment

It’s possible to redirect your URL with no fregment to URL with fregment using RewriteRule directive in htaccess.

RewriteEngine on
RewriteRule ^foobar$ /file.php#foobar [R,NE]

The rule above will successfully redirect your URL path from /foobar to /file.php#foobar but doing the opposite redirection
for example /file.php#foobar to /foobar isn’t possible by any server side redirection means.

The NE flag in the RewriteRule above is important to avoid the # getting charged to its hex. If the NE flag is removed the the rule will redirect /foobar to /file.php%23oobar which can cause server errors.

So finally, you can use RewriteRule to redirect your URLs (without fregment) to the one that has fregment. You can use a fregment path in the substitution string of a RewriteRule with R and NE flags but you can’t use a fregment path in the pattern of a RewriteRule because # and anything after it isn’t sent to server.

You can use JavaScript to redirect URI fregments

Since fregment is maintend by a client, the solution to redirect a fregment path is by using a client-side redirect logic.
The best way to redirect a fregment path is JavaScript .
The following JavaScript based redirection can redirect your current page with #foobar to https://example.com/ :


I hope this article was helpful! Thank you so much for reading!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.