How can I define rewrite rule to accept also empty string in addition to a-zA-Z-?

Viewed 257

I'm using rewrite rules in a htaccess to define particular strings which, when placed in an url opens specific pages.

e.g. in this case category name and product name

RewriteRule ^products/([a-zA-Z-]+)/([a-zA-Z-]+)$        /products.php?kat_name=$1&prod_name=$2

So when given URL is e.g. /products/shirts/t-shirt everything works fine. But when URL is /products//t-shirt, the rule doesn't work, because of empty string after the first slash.

How can I modify my rule to accept also empty pattern after the first slash?

Sorry I'm not very familliar with rewrite rules.

Thanks and best regards

2 Answers

You can make use of optional matching in a non-capture group:

Options -MultiViews
RewriteEngine On

RewriteRule ^products/(?:([a-z-]+)/)?([a-z-]+)/?$ products.php?kat_name=$1&prod_name=$2 [L,QSA,NC]

This will following matches:

  • /products/shirts/t-shirt => $_GET:
    [kat_name] => shirts
    [prod_name] => t-shirt
  • /products//t-shirt => $_GET:
    [kat_name] => 
    [prod_name] => t-shirt

I've now found a better solution on the web myself by using the * operator instead the +

This allows also to leave the value empty:

RewriteRule ^products/([a-zA-Z-]*)/([a-zA-Z-]+)$        /products.php?kat_name=$1&prod_name=$2
Related