Rewriting URL encoded hash character with htaccess

.htaccessmod-rewrite

I have a single page website that uses the hash (#) to access different pages.
The problem is that some PDF viewers break my links encoding the hash character, replacing # with %23, so for example the link my.app.com/#product/22 becomes my.app.com/%23product/22.
I'm trying to correct this using an htaccess rule that rewrites the URL:

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

but it doesn't seem to work, what can I do?

Best Answer

The RewriteRule pattern matches against the %-decoded URL-path. So, if the requested URL contains %23 (a URL encoded #) then you need to match a literal # in the RewriteRule pattern. Otherwise, your redirect seems to be OK.

For example:

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

The NE (noescape) flag is required here in order to prevent the # in the substitution being URL encoded in the redirect response.

Clear your browser cache before testing. And test with 302 (temporary) redirects to avoid caching issues.