Maybe is best way to show my problem in one example.

In my .htaccess :

RewriteRule ^catalog/[a-z0-9_-]+-([0-9]+)/[a-z0-9_-]+-([0-9]+)/[a-z0-9_-]+-([0-9]+)/  index.php?act=catalog&category=$1&color=$2&size=$3 [NC,L]

With the address www.site.com/catalog/category-1/red-3/size-3/ this works excellent

But if you leave out the size, like www.site.com/catalog/category-1/red-3/, I will be redirected to www.site.com.

I want to show all articles with category ID 1 and color which is ID 3.

  • for syntax errors : lyxx.com/freestuff/002.html
    – Eray
    Jun 19, 2011 at 20:27
  • So you're saying you want the last directory, e.g. size-3, to be optional?
    – Jason McCreary
    Jun 19, 2011 at 20:27
  • Yes .. can i set some directory to be optional ??
    – user778441
    Jun 19, 2011 at 20:31

2 Answers 2


You can have optional parts, if your PHP script accepts an empty size parameter and then does what you want.

Try this:

RewriteRule ^catalog/[a-z0-9_-]+-([0-9]+)/[a-z0-9_-]+-([0-9]+)/([a-z0-9_-]+-([0-9]+)/)?  index.php?act=catalog&category=$1&color=$2&size=$4 [NC,L]

The important changes are one more parenthesized group, followed by an ? (to make it optional), and an adaption of the capture number from $3 to $4 (since the capturing group for the size is now the 4th one). (Instead of the number change we could also have used (?: instead of the added (, I guess.)


You will need to write another rewrite rule to match the option of not having a size specified:

RewriteRule ^catalog/[a-z0-9_-]+-([0-9]+)/[a-z0-9_-]+-([0-9]+)/ index.php?act=catalog&category=$1&color=$2 [NC, L]

Put that as your second rewrite since it is the least specific.

  • I would like to define a directory as an optional if possible
    – user778441
    Jun 19, 2011 at 20:35
  • You are going to need two rewrite rules, one that matches one regexp and one that matches the other. I'll update my answer with more info
    – Connor Smith
    Jun 19, 2011 at 20:38
  • You can't necessarily set one as optional, you just have to make more lines to match all possible options (:
    – Connor Smith
    Jun 19, 2011 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.