Lemon Drop
Lemon Drop

Reputation: 2133

.htaccess Internal Redirect issue

Something with my .htaccess file is creating a rule loop of some sort when a certain condition exists. Here is the code in question:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule ^(.+)/?$ /%1.php?o=$1 [L,NC,QSA]

RewriteCond %{HTTP_HOST} ^(.*)\.example\.com$ [NC]
RewriteRule ^$ /%1.php [L,NC,QSA]
</IfModule>

Normally what this does is:

test.example.com -> example.com/test.php
test.example.com/test2 -> example.com/test.php?o=test2

Thats fine, except when the "test" subdomain part points to a nonexistent file, I get an internal redirect error, specifically this:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace., referer: [retracted]

Any help is appreciated.

Upvotes: 1

Views: 86

Answers (1)

anubhava
anubhava

Reputation: 785196

Yes it will cause looping because RewriteCond %{REQUEST_FILENAME} !-f will still be true for /test.php when /test.php doesn't exist.

You can use this code to prevent looping:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# don't redirect after one internal redirect
RewriteCond %{ENV:REDIRECT_STATUS} .+
RewriteRule ^ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule ^(.+?)/?$ /%1.php?o=$1 [L,QSA]

RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule ^$ /%1.php [L]
</IfModule>

Upvotes: 1

Related Questions