Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
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 = Designer. Developer. Producer. Writer. Editor. Etc.
The Tao of WordPress: Master the art of WordPress.
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 »
.htaccess made easy: Improve site performance and security.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
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
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.