Joel
Joel

Reputation: 6107

Regex to handle '/' trim in URL

I am using the following rewrite rule:

RewriteRule ^search/(.*)/(.*) search.php?letter=$1&num=$2 [NC,L]

It works fine when loading "/search/a/1" in the browser, meaning that when debugging with PHP the values of the vars are: $letter='a' and $num=1 .

However, when loading "/search/a/1/" (with ' / ' at the end), the values of the vars are: $letters='a/1' and $num=NULL .

What regex should I use to make both "/search/a/1" and "/search/a/1/" result in the same way?

Thanks,

Joel

Upvotes: 1

Views: 114

Answers (2)

Kobi
Kobi

Reputation: 138007

Try:

RewriteRule ^search/([^/]*)/([^/]*) search.php?letter=$1&num=$2 [NC,L]

This makes sure the groups $1 and $2 never contain a slash. The regex allows martial matching (no $ at the end), so it will ignore further tokens: /search/a/1/blah/blah should work as expected.

To allow only a single slash at the end, and nothing more (make sure you don't have .* in other rules, of course):

RewriteRule ^search/([^/]*)/([^/]*)/?$ search.php?letter=$1&num=$2 [NC,L]

Upvotes: 1

al.
al.

Reputation: 717

You're matching any character ., but want to match any character but a slash [^/], so:

RewriteRule ^search/([^/]*)/([^/]*) search.php?letter=$1&num=$2 [NC,L]

Upvotes: 1

Related Questions