Webmasters Stack Exchange is a question and answer site for pro webmasters. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
RewriteRule ^([A-Za-z0-9_\-]+)$ /userviewproducts.php?category=$1 [L]
RewriteRule ^([A-Za-z0-9_\-]+)/$ /userviewproducts.php?category=$1 [L]
RewriteRule ^([A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+)$ /userviewproducts.php?category=$1 [L]
RewriteRule ^([A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+)/$ /userviewproducts.php?category=$1 [L]
RewriteRule ^([A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+)$ /viewbuyproduct.php?1=$1 [L]
RewriteRule ^([A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+)/$ /viewbuyproduct.php?1=$1 [L]

I have next rules. They work in that way:

if url = /a or /a/ or /a/a or /a/a/ go to file userviewproducts.php
and if url = /a/a/a or /a/a/a/ go to file viewbuyproduct.php

It works as i need, but i see the CODE-SMELLS term here and want to write it shorter. Will plus every answer =)

share|improve this question
Anyway I belive these type of questions should be posted on Stackoverflow. You are gonna get more valuabel answers there. – Marco Demaio Dec 18 '10 at 18:08
up vote 2 down vote accepted

Try this:

RewriteRule ^([A-Za-z0-9_\-]+)/?$ /userviewproducts.php?category=$1 [L]
RewriteRule ^([A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+)/?$ /userviewproducts.php?category=$1 [L]
RewriteRule ^([A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+/[A-Za-z0-9_\-]+)/?$ /viewbuyproduct.php?1=$1 [L]

It's shorter.

share|improve this answer
Whoops, I left the page open for 20 minutes and ended up posting the same answer as you ;) – DisgruntledGoat Dec 17 '10 at 13:41

Read up on Regular Expressions. A better understanding of them will help you write shorter rules here and in future.

You can use a regular expression tool to experiment with different rules and see how they match.

I am sure you can get it down to two lines - one for each outcome that you want. The lines might be longer though :-)

share|improve this answer

This could be further simplified to:

RewriteRule ^([\w-]+(/[\w-]+)?)/?$ /userviewproducts.php?category=$1 [L]
RewriteRule ^([\w-]+/[\w-]+/[\w-]+)/?$ /viewbuyproduct.php?1=$1 [L]

\w is shorthand for [A-Za-z0-9_].

The - (hyphen) does not need to be escaped when used at the start or end of the character class.

The ? at the end makes the preceding slash optional.

Finally, the first two rules (substitutions) are combined by making the second part of the pattern optional. ie. (/[\w-]+)?. $1 still matches the whole URL-path, less the trailing slash (if any).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.