mod_rewrite & PHP: How to match urlencoded plus sign (+ = %2B)

I ran into trouble when trying to pass a urlencode()‘ed plus sign into a web address being processed by mod_rewrite.

$url = '';
$url = urlencode($url); //

This $url variable gets echo()‘d as a link in a page, so once it’s clicked and loaded in the browser, I then needed mod_rewrite to translate that to the actual URL, which is:

Here is the RewriteRule I was using to match:

# match any name containing any combination of letters, numbers, and the % sign (to match urlencoded URLs)
RewriteRule ^browsealpha/([%\w]*)/?$ /browsealpha.php?name=$1 [QSA,L]

This rule should match but for some reason it wouldn’t work. After hours of frustration, I found a few threads mentioning the need to urlencode() the string twice, like so:


IT WORKS!!! Apparently this is because mod_rewrite automatically decodes the urlencoded URL, so if you pass in %2B, PHP sees it as %2B0. If you double encode, mod_rewrite decodes the first one, and PHP receives the second one (which is now %2B, which is what we want).

Now playing: Autechre – 444
via FoxyTunes