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?
CodePudding user response:
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
- Since your URI is starting with
/compare
and rule is rewriting tocompare.php
you need to turn off content negotiation by turning offMultiViews
. - Your last rule is without any
RewriteCond
as that is only applicable to next immediateRewriteRule
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]