Using hashmarks for URL anchors in Apache rewrites
Today I had to make an Apache rewrite that redirected a custom URL not only to a different page, but also to a specific anchor link on the destination page. In other words, /foobar
had to actually load /some/other/url#foobar
.
However, by default Apache rewrites will escape the hash (#)
symbol, converting to its hexcode equivalent %23
.
So this rewrite…
RewriteRule ^/foobar/?$ /some/other/url#foobar/ [R=301,L]
will produce this URL…
http://example.com/some/other/url%23foobar
In order to make this rewrite work, we must prevent Apache from escaping the hash mark by using the noescape
flag. A little tweak to the rewrite, and we’re good to go…
RewriteRule ^/foobar/?$ /some/other/url#foobar/ [R=301,L,NE]
See that little NE
on the end? That’s all we need to make rewrite anchors work.
Documentation on all the rewrite flags can be found in the Apache docs for the RewriteRule Directive.