Super Plugin Sale! Your Choice: BOGO or 30% Off »
Web Dev + WordPress + Security

Redirecting Hash Fragments with .htaccess

During this year’s site redesigns, I noticed in the server logs some 404 errors for various WordPress comments. These 404 requests each involved a fragment identifier (i.e., character string beginning with a pound sign, #) being interpreted as its HTML entity hex equivalent, %23. It may not seem like a big deal, but these days every detail counts, so it’s wise to clean up as many 404 errors as possible. Thus, here is a simple .htaccess technique for redirecting hash-fragment requests to their proper destination.

WordPress Example

The logs were showing numerous requests where the hash symbol # was replaced with its HTML character code, %23. These were interpreted literally, such that the requested URLs were recorded as such:

https://example.com/some-path/%23comment-61814

To fix this with .htaccess, we can do this:

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

Here we are rewriting the request such that the correct path and comment number are specified in the redirect URL. So 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 equivalent %23 during the rewrite.

General Example

This technique can be applied to the general case. Let’s say you want to redirect /example/%23identifier to /example/#identifier. It’s as easy as adding this to your .htaccess file:

RewriteRule ^/example/%23identifier /example/#identifier [R=301,L,NE]

Or let’s say that we want to redirect such that a part of the URL is appended as a hash fragment:

RewriteRule ^/some-path/(.*)/?$ /some-path/#$1 [R=301,L,NE]

So for example, if the request is for /some-path/whatever/, it will be redirected to /some-path/#whatever.

Again, the NE flag is instrumental to making this happen.

About the Author
Jeff Starr = Fullstack Developer. Book Author. Teacher. Human Being.
Banhammer: Protect your WordPress site against threats.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
BBQ Pro: The fastest firewall to protect your WordPress.
Thoughts
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Crazy that we’re almost halfway thru 2024.
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.