Mansur Khan
Mansur Khan

Reputation: 1675

optional parameter in url rewriting

I'm using apache and .htacess to rewrite my urls.

I would like to have an optional parameter "mess" in my ad.php page. I wrote :

RewriteRule    ^ad-([A-Za-z0-9-]+)/?$    ad.php?id=$1    [NC,L]
RewriteRule    ^ad-([A-Za-z0-9-]+)-([A-Za-z0-9-]+)/?$    ad.php?id=$1&mess=$2    [NC,L]

But it seems that only the first rule is considered. ad-100 and ad-100-1 should give different things but they don't. When I remove The first Rule, ad-100 is not working anymore (obviously) and ad-100-1 is now working because it's taking the second rule.

Do you know how I can have optional parameters ? Should I combine the two rule in one ?

Upvotes: 0

Views: 1159

Answers (1)

Felipe Alameda A
Felipe Alameda A

Reputation: 11809

This should work:

RewriteCond %{REQUEST_URI}             !ad\.php              [NC]
RewriteRule    ^ad-([^-]+)/?$           ad.php?id=$1         [NC,L]
RewriteCond %{REQUEST_URI}             !ad\.php              [NC]
RewriteRule    ^ad-([^-]+)-([^/]+)/?    ad.php?id=$1&mess=$2 [NC,L]

Optionally, you could use one rule for both parameters if there is no problem having mess value empty when there is only one parameter. Like this:

RewriteCond %{REQUEST_URI}             !ad\.php              [NC]
RewriteRule    ^ad-([^-]+)-?([^/]+)?/? ad.php?id=$1&mess=$2  [NC,L]

Upvotes: 2

Related Questions