Prevent redirect loop in mod_rewrite

Posted by user280381 on Server Fault See other posts from Server Fault or by user280381
Published on 2012-11-21T12:48:47Z Indexed on 2012/11/22 5:02 UTC
Read the original article Hit count: 418

I'm writing a rule in my htaccess that basically says this:

  • If the request is for the homepage
  • And a cookie has not been set
  • Rewrite the page with /addCookie.php

Then in addCookie.php, we set the cookie and redirect back to the homepage. This is all fine, but if the user doesn't accept cookies, we get an infinite loop of redirects.

I'm new to mod_rewrite, I've done a lot of searching, but can't break the loop. I have this so far:

  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [S=1]

  RewriteCond %{REQUEST_URI} "^/$"
  RewriteCond %{HTTP_COOKIE} !device_detected
  RewriteRule ^ addCookie.php [L]

Is what I'm trying to do possible? I could add a query string on the redirect from addCookie.php, but I'd much rather keep the requests identical.

Any suggestions kindly welcome.

© Server Fault or respective owner

Related posts about .htaccess

Related posts about mod-rewrite