How to prevent URL double encoding/escaping

In a recent project, I’ve been involved on we hit the problem of the server double encoding the URL. It was an e-commerce website, with a shop made on top of OpenCart, with a search option (a simple input box). When you were typing a two work keyword in there, the server was encoding the blank space two times: meaning that instead of encoding it to %20 it was displaying it as %2520 — basically, it was encoding the % again.

After trying different approaches to enforcing UTF8, to do some code changes, etc and spending 3–4 hours on this, found this very easy solution that saved the day.

I was a simple change in the .htaccess file that was responsible for redirect non-www to www.

Before the change:

    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

All it had to be change was to add the NE (no escape) flag which will force mod_rewrite to leave all query string values as they are, without doing any encoding / escaping.

So, after changes, this would look like:

    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,NE,L]

Hope this might save time for others.

If you like this one, please share, recommend or comment on different approaches /opinions 🙂

If you like this and find it useful please consider sharing it! Cheers!Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn