RewriteRule with optional parameter for redirection in .htacces

Viewed 40

I would like to rewrite from:

www.domain.de/123/hello

to:

www.domain.de/index.php?a=$1&b=$2

I have this rule:

RewriteEngine On
Options +FollowSymlinks 
RewriteBase / 

RewriteRule ^([^/]+)/([^/]+)?$ index.php?a=$1&b=$2 [L,QSA,NC]

it works fine. But I also would like that it also works with the input:

www.domain.de/123

(Here I will get an 404 error.) The &b shout be empty in this case. How to achive this?

1 Answers

You may use these rules with an optional match for 2nd paramter:

RewriteEngine On
Options +FollowSymlinks 
RewriteBase / 

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)(?:/([^/]+))?/?$ index.php?a=$1&b=$2 [L,QSA]

Here (?:/([^/]+))? is an optional match to make sure above rule matches both:

www.domain.de/123/hello

and

www.domain.de/123 
Related