99tharun 99tharun - 1 year ago 60
PHP Question

How to handle special characters like & and / in .htaccess rules?

In my .htaccess file I have defined following rule,

RewriteRule ^([-0-9a-zA-Z]+) search.php?id=$1

The above rule works fine if I am browsing http://example.com/abcd
I need to use the symbols
& % - /
in the url like: http://example.com/ab&cd

What changes have to be made to the rule for this to work?

Answer Source

No idea how that rule is working for you. First, it loops. Second, there is no capture groups for $2 and $3, but it doesn't matter because $1 is always "search" anyways. I'm assuming you've pasted a partial snippet of a rule that you have that works.

The reason why &, %, or / isn't being matched is because your regex says:


which means: one or more letters, numbers, or a dash. So no &, %, or /. So you can add those into the square brackets:

RewriteRule ^([-0-9a-zA-Z/%&]+) search.php?id=$1&ff=$2&ffid=$3

However, keep in mind that the URI is decoded before any rules get applied. This means if the URI looks like:


You don't need to match against %, because the URI gets decoded into:


and you need to match against (. A better option may to just match against every except dots:

RewriteRule ^([^.]+) search.php?id=$1&ff=$2&ffid=$3

or whatever you don't want in your match.


RewriteRule ^([^.]+)$ search.php?id=$1 [B]

The difference here is the $ to bound the match to the end of the URI, and the B flag ensures the & gets encoded.