Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop RewriteEngine/PHP redirect loop?

The task seems very simple:

all requests must be passed through one file.

However,

when following code is added to httpd.conf:

RewriteEngine On  
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?route=$1 [QSA,R=301,L]

and following code is added to /index.php:

if( isset($_GET["route"]) && $_GET["route"] != "/index.php" ){
header("Location: ".$_GET["route"]);
}

then it causes redirect loop!

Causes for example such loop:

www.site.com/image.jpg -> (redirected by httpd.conf)

www.site.com/index.php?route=/image.jpg -> (redirected by index.php)

www.site.com/image.jpg -> (redirected by httpd.conf)

www.site.com/index.php?route=/image.jpg -> (redirected by index.php)

...

So, the question is following:

How to stop this loop?

To stop for example in such way:

www.site.com/image.jpg -> (redirected by httpd.conf)

www.site.com/index.php?route=/image.jpg -> (redirected by index.php)

www.site.com/image.jpg (no further redirection)

like image 906
valeryan Avatar asked Feb 17 '26 03:02

valeryan


1 Answers

This one is a bit of patch, but I think it works.

httpd.conf:

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{QUERY_STRING} !^(.*)a=a$ [NC]
RewriteRule ^(.*) index.php?route=$1 [QSA,L]

index.php:

<?php
if( isset($_GET["route"]) && $_GET["route"] != "/index.php" ){
    header("Location: ".$_GET["route"].'?a=a');
}

The thing is: First time the rewrite engine redirects the page to index.php. Then, in index.php there's a redirection to the same file but adding parameter a=a. Then rewrite engine comes again, but he has orders of not redirect when found the string a=a in the query string, and there's no further redirection.

Of course this will end in a 404 error, since you're filtering only non-existant files with the first two rewritecond, but I guess you know how to deal with that.

like image 132
Amarnasan Avatar answered Feb 18 '26 18:02

Amarnasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!