1
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 =)

  • 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
2

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.

|improve this answer|||||
  • 1
    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
1

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 :-)

|improve this answer|||||
0

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).

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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