99tharun 99tharun - 5 months ago 23
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

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:

[-0-9a-zA-Z]+

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:

/foo%28bar

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

/foo(bar

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.


Try:

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.

Comments