Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 475
99tharun Avatar asked Oct 20 '25 15:10

99tharun


2 Answers

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.

like image 157
Jon Lin Avatar answered Oct 22 '25 03:10

Jon Lin


Do with your url

RewriteRule ^directory/([^/.]+)$ /searchpage.php?search_keywords=$1  [L]
like image 33
coder007 Avatar answered Oct 22 '25 04:10

coder007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!