Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 0 down vote accepted

Yes, that's impossible; the REDIRECT_STATUS won't be present when the client is the one handling the redirect (from the addCookie.php location back to /).

Why not simply set a cookie as part of your home page handling if one wasn't sent by the client, and potentially harass the user if they didn't accept the cookie and it's needed for your application?

share|improve this answer
Okay, thanks for clearing that up. The home page is a static html file, so I'm looking at using ajax to set the cookie instead. – user280381 Nov 22 '12 at 21:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.