.htaccess mod_rewrite loop
I am working on implementing some mod_rewrite.htaccess rules for generating clean urls. Specifically, when a user submits a form with a GET request, I try to make sure the url is cleaned up with a 301 (currently testing is done with a 302 to avoid caching).
The problem is that my rules are creating an infinite loop.
The rule to redirect the user's request (to not see the user? Query1 = & query2 = in your browser):
RewriteCond %{QUERY_STRING} ^query1=(.*)&query2=(.*)$ [NC]
RewriteRule ^results.php$ /results/%1/%2? [R=302,NC,L]
However, I also have a rule to further format any visit / results / to navigate to results.php (for example from the "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 issue?
Thank!
source to share
Rewrites the engine, so the last rule that gets rewritten into the query string is trapped by the first rule as the loop moves. Instead of mapping to a variable, %{QUERY_STRING}
you need to map to a variable %{THE_REQUEST}
so that it doesn't depend on 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>
source to share