Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess mod_rewrite loop

I am working on implementing some mod_rewrite .htaccess rules to create clean URLs. Specifically, when a user submits a form with a GET request, I am trying to ensure the URL is cleaned via a 301 (currently testing with a 302 to avoid caching).

The problem I have is that my rules are creating an infinite loop.

The rule to redirect the user's get request (to avoid the user seeing ?query1=&query2= in their browser):

RewriteCond %{QUERY_STRING} ^query1=(.*)&query2=(.*)$ [NC]
RewriteRule ^results.php$ /results/%1/%2? [R=302,NC,L]

However, I also have a rule further down to format anyone visiting /results/ to forward to results.php (e.g. from a "back to results" link):

RewriteRule results/(.*)/(.*)$ results.php?query1=$1&query2=$2 [NC,L]

Full .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{QUERY_STRING} ^query1=(.*)&query2=(.*)$ [NC]
    RewriteRule ^results.php$ /results/%1/%2? [R=302,NC,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule results/(.*)/(.*)$ results.php?query1=$1&query2=$2 [NC,L]
</IfModule>

Any suggestions as to how I can fix this problem?

Thanks!

like image 758
square Avatar asked Jul 13 '26 00:07

square


1 Answers

The rewrite engine loops, so your last rule that rewrites to the query string gets trapped by the first rule when the engine loops. Instead of matching against the %{QUERY_STRING} variable, you need to match against the %{THE_REQUEST} variable so that it's not affected by other rewrites:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{THE_REQUEST} /results\.php\?query1=([^&]+)&query2=([^&\ ]+) [NC]
    RewriteRule ^results.php$ /results/%1/%2? [R=302,NC,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule results/(.*)/(.*)$ results.php?query1=$1&query2=$2 [NC,L]
</IfModule>
like image 71
Jon Lin Avatar answered Jul 17 '26 15:07

Jon Lin



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!