Home > Enterprise >  rewrite rule for single or multiple folders
rewrite rule for single or multiple folders

Time:04-12

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:

  1. .* in first rule is too greedy which matches a / so first rule is also matching /compare/car/india as well as /compare/car
  2. Since your URI is starting with /compare and rule is rewriting to compare.php you need to turn off content negotiation by turning off MultiViews.
  3. Your last rule is without any 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]
  • Related