My htaccess code for URL rewrite:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^compare/(.*)/?$ compare.php?page=$1 [L,QSA]
RewriteRule ^compare/(.*)/(.*)?$ compare.php?page=$1&location=$2 [L,QSA]
This rule works for :
www.example.com/compare/car
But it is not working for:
www.example.com/compare/car/india
I want to modify the rewrite rule which works for these urls:
www.example.com/compare/car
www.example.com/compare/car/india
Is it possible? How can I modify my rewrite rule to achieve this?
There are 2 problems with your code:
.*
in first rule is too greedy which matches a /
so first rule is also matching /compare/car/india
as well as /compare/car
/compare
and rule is rewriting to compare.php
you need to turn off content negotiation by turning off MultiViews
.RewriteCond
as that is only applicable to next immediate RewriteRule
directive.You may use this code in your site root .htaccess:
Options -MultiViews
RewriteEngine On
RewriteBase /
# skip all files and directories from rewrite
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# one path element after compare
RewriteRule ^compare/([^/]+)/?$ compare.php?page=$1 [L,QSA,NC]
# two path elements after compare
RewriteRule ^compare/([^/]+)/([^/]+)/?$ compare.php?page=$1&location=$2 [L,QSA,NC]