nick
nick

Reputation: 3259

Apache mod_rewrite rules not meeting

I'm trying to transform this URL

http://www.example.com/test/products-list.php?category=cars&subcategory=coupe&color=blue

to

http://www.example.com/test/products/cars/coupe/blue

These are the rules I'm using:

RewriteRule products/(.*)/(.*)/(.*)/ /test/products-list.php?category=$1&subcategory=$2&color=$3
RewriteRule products/(.*)/(.*)/(.*) /test/products-list.php?category=$1&subcategory=$2&color=$3

It works for some URLs:

http://www.example.com/test/products/cars ----> not working
http://www.example.com/test/products/cars/ ----> not working
http://www.example.com/test/products/cars/coupe ----> not working
http://www.example.com/test/products/cars/coupe/ ----> working
http://www.example.com/test/products/cars/coupe/blue ----> working
http://www.example.com/test/products/cars/coupe/blue/ ----> working

How can I fix those 3 cases in which it doesn't work? Also, what's the reason it's not working?

Upvotes: 0

Views: 32

Answers (1)

Craig
Craig

Reputation: 63

I think that your expression is looking for 3 or 4 '/' after the word products.

Your three captures (.*) are using the "0 or more" repetition operator '*', but your three /'s are required.

I believe that http://www.example.com/test/products/cars// will test as working.

Now... how to fix it?

I imagine you will need three different rewrites for each search case.

  1. category
  2. category and subcategory
  3. category, subcategory and color

You will see below that I have used the '+' 'repetition operator' to force at least a 1 character in the captures for category, subcategory, or color.

The '/?' on the end of the expressions indicates that the '/' is optional. This will combine your two rules above into one.

RewriteRule products/(.+)/? /test/products-list.php?category=$1
RewriteRule products/(.+)/(.+)/? /test/products-list.php?category=$1&subcategory=$2
RewriteRule products/(.+)/(.+)/(.+)/? /test/products-list.php?category=$1&subcategory=$2&color=$3

Note to reader, I haven't done Apache mod_Rewrite for many years, but I think that it is just a regular expression matching problem.

Upvotes: 1

Related Questions