: 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_-]+)$
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 =)
More posts by @Michele947
3 Comments
Sorted by latest first Latest Oldest Best
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).
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.
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 :-)
Terms of Use Create Support ticket Your support tickets Stock Market News! © vmapp.org2024 All Rights reserved.