Mobile app version of vmapp.org
Login or Join
Michele947

: Simplify URL rewrites in .htaccess? RewriteRule ^([A-Za-z0-9_-]+)$ /userviewproducts.php?category= [L] RewriteRule ^([A-Za-z0-9_-]+)/$ /userviewproducts.php?category= [L] RewriteRule ^([A-Za-z0-9_-]+/[A-Za-z0-9_-]+)$

@Michele947

Posted in: #Apache #Htaccess #ModRewrite

RewriteRule ^([A-Za-z0-9_-]+)$ /userviewproducts.php?category= [L]
RewriteRule ^([A-Za-z0-9_-]+)/$ /userviewproducts.php?category= [L]
RewriteRule ^([A-Za-z0-9_-]+/[A-Za-z0-9_-]+)$ /userviewproducts.php?category= [L]
RewriteRule ^([A-Za-z0-9_-]+/[A-Za-z0-9_-]+)/$ /userviewproducts.php?category= [L]
RewriteRule ^([A-Za-z0-9_-]+/[A-Za-z0-9_-]+/[A-Za-z0-9_-]+)$ /viewbuyproduct.php?1= [L]
RewriteRule ^([A-Za-z0-9_-]+/[A-Za-z0-9_-]+/[A-Za-z0-9_-]+)/$ /viewbuyproduct.php?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 =)

10.03% popularity Vote Up Vote Down


Login to follow query

More posts by @Michele947

3 Comments

Sorted by latest first Latest Oldest Best

 

@Ann8826881

This could be further simplified to:

RewriteRule ^([w-]+(/[w-]+)?)/?$ /userviewproducts.php?category= [L]
RewriteRule ^([w-]+/[w-]+/[w-]+)/?$ /viewbuyproduct.php?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-]+)?. still matches the whole URL-path, less the trailing slash (if any).

10% popularity Vote Up Vote Down


 

@Lee4591628

Try this:

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


It's shorter.

10% popularity Vote Up Vote Down


 

@Becky754

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

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme