Yif Swery
Yif Swery

Reputation: 179

Two RewriteCond and RewriteRule working independently

So I have two rules. Each rule does exactly what it should when its in the .htaccess by itself, but when both rules are there they start to conflict with each other.

RewriteCond %{REQUEST_URI} ^(.*)\.html$
RewriteRule ^(.*)\.html$ index.php?id=$1 [QSA,L]

The above rule works fine for getting say http://domain.com/12.html and passing the number 12 into index.php only if the number finishes with .html (note 12.html file does not exist!)

RewriteCond %{REQUEST_URI} !^(.*)\.html$
RewriteRule ^(.*)$ /$1\.html [L,R=301]

This works fine for checking if the URL ends with .html. And if it DOES NOT finish with .html, it will redirect it to the URI + .html (this also works fine by itself).

When I have both rules in the one .htaccess

RewriteCond %{REQUEST_URI} ^(.*)\.html$
RewriteRule ^(.*)\.html$ index.php?id=$1 [QSA,L]

RewriteCond %{REQUEST_URI} !^(.*)\.html$
RewriteRule ^(.*)$ /$1\.html [L,R=301]

then there is a loop resulting in a redirect loop.

Can someone please point out where I am going wrong?

Upvotes: 1

Views: 598

Answers (1)

Neil
Neil

Reputation: 55402

So, the first rule rewrites http://domain.com/12.html into http://domain.com/index.php?id=12. Then things start going awry; the second rule rewrites that into http://domain.com/index.php.html?id=12, but at that point I think you'll find that the first rule kicks in again, rewriting that into something like http://domain.com/index.php?id=index.php, which the second rule rewrites into http://domain.com/index.php.html?id=index.php. At this point I think the rules end up fighting over the URL.

The easiest solution is probably to tweak the second rewrite rule not to rewrite pages that already contain an extension, i.e. use [^.]* instead of .*.

Upvotes: 1

Related Questions