Wednesday, February 19, 2020

Apache rewrite rule to replace %20-%20 with a dash (#) in URLs

Some old(?) versions of Microsoft Excel replace a dash (#) in an URL with "%20-%20". The following example shows, how Excel transforms URLs:

Original URL:

URL when clicked in Excel:

This may lead to unexpected behavior on webserver application level e.g. when routing can not be resolved successfully and the request will results in an 404 error.

The probably best way would be to fix this behavior "somehow" in Excel, but this does not always seem to be possible as described in this stackoverflow question.

In order work around this problem for a certain application on a webserver, I added a simple redirect which replaces the "%20-%20" with a "#" using the following .htaccess rewrite rule:

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

This is for sure not a general solution for the problem, put works perfectly when you only have to fix incoming links for a given application.