1
votes

www.example.com/category/sub_category/Having problem with the rewririte rules in .htaccess file.

my current .htaccess file looks like this.

RewriteRule ^([0-9a-zA-Z_-]+)/([0-9]+)$ products.php?cat=$1&id=$2 [NC,L]
RewriteRule ^([^/]*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_categories.php?cat=$2&id=$3 [NC,L]
RewriteRule ^(.*)/(.*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_details.php?cat=$3&id=$4 [NC,L]
RewriteRule ^([0-9]+)$  gallery.php?id=$1 [NC,L]

I'm trying create urls like the following.

www.example.com/product_name/1
www.example.com/category/sub_category/21
www.example.com/category/sub_category/product_name/233
www.example.com/gallery/872

www.example.com/gallery/872 is redirecting to www.example.com/category/sub_category/872 instead of gallery.php?id=872

edit:corrected url from www.example.com/gallery/872 to www.example.com/category/sub_category/872.

2
The example you posted as last line does not make sense. That would mean no redirection at all is done. You probably want to fix that line in your question. (note: there is an edit button below your question...) - arkascha
@arkascha sorry about that. I have corrected the links. - Night Lord
OK, that makes more sense :-) I'd say your issue is that the first rule matches, the last one can never get applied... - arkascha

2 Answers

2
votes

Your issue is that the first rule matches, the last one can never get applied...

RewriteEngine on
RewriteRule ^gallery/([0-9]+)/?$  gallery.php?id=$1 [NC,L]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9]+)$ products.php?cat=$1&id=$2 [NC,L]
RewriteRule ^([^/]*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_categories.php?cat=$2&id=$3 [NC,L]
RewriteRule ^(.*)/(.*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_details.php?cat=$3&id=$4 [NC,L]

Rule of thumb: first the specific exceptions, then the more general rules.

The NC flag does not make sense if you also specify both, lower and upper case letters in your regex patterns. It is either/or, not and.

(note: I also included the correction @anubhava posted in his answer)

0
votes

Your last rule will need regex modification since you're matching /gallery/872 and your pattern is only matching 1 or more digits.

RewriteRule ^gallery/([0-9]+)/?$ gallery.php?id=$1 [NC,L,QSA]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9]+)$ products.php?cat=$1&id=$2 [QSA,L]
RewriteRule ^([^/]*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_categories.php?cat=$2&id=$3 [QSA,L]
RewriteRule ^(.*)/(.*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_details.php?cat=$3&id=$4 [QSA,L]

Also you need to recorder your rules like I showed above.