Mod Rewrite Apache 2 and ampersands
Posted in Technical on September 27th, 2011 by iyoung – Be the first to commentI had an annoying little problem today, I wanted to translate a URL like this:
http://mysite.com/baskets/ians/ian & co.xml
into
http://mysite.com/cgi/baskets_handler/?state=show_basket&username=ians&basket=ian%20%26%20co&ret_type=xml
Using mod rewrite, although ampersands in the URL in this way are dirty and in this case very rare as the interface does not allow the creation of baskets with an ampersand I wanted to handle them just incase.
If it had just been spaces in the basket name I would have just used RewriteMap escapemap int:escape but it always leaves ampersands and passes them through unescaped so they are interpretted as part of the query string.
I ended up with the following, any suggestions on better ways to do it would be gratefully received, please post as a comment:
RewriteCond %{REQUEST_URI} ^/baskets [NC]
RewriteRule ^([^&]*)&(.*) $1\%26$2 [N]
RewriteCond %{REQUEST_URI} ^/baskets [NC]
RewriteRule ^([^\s]*)\s(.*) $1\%20$2 [N]
RewriteRule ^/baskets/([^/]+)/([^/\.]+)(\.(xml|json))?$ http://%{HTTP_HOST}/cgi/basket_handler/?state=show_basket&user=$1&basket=$2&ret_type=$4 [P]