How to do htaccess redirect based on cookie value

I have failed at Google and I could not find the answer searching here. Sorry, I'm a newb at htaccess and it has really odd syntax and is so hard to learn!

You can see what I'm trying to do here...

RewriteEngine on
RewriteCond %{HTTP_COOKIE} ^.*user_id=(\d+).*$ [NC]
RewriteRule .* http://localhost/mysite/cache/$1 [R=301,L]
RewriteRule .* http://localhost/mysite/cache/guest [R=301,L]

I'm caching the pages for each user for load speed. I want to redirect to the proper HTML cache folder if they're logged in with a cookie, otherwise I want to load the guest cache.

Right now it goes into an infi-loop. If I remove the [R=... then I get internal server error.

Please help!!! THank you!!!


This works for a cookie like id=1234:

RewriteEngine on
RewriteCond %{HTTP_COOKIE} ^id=([0-9]*)$ [NC]
RewriteRule .* http://localhost/mysite/cache/%1 [R=301,L]
RewriteRule .* http://localhost/mysite/cache/guest [R=301,L]

Now for your problem: Make sure that your htaccess does not apply to the page you rewrite to! For example, if your .htaccess lies in /mysite/.htaccess

It will be used again in

http://localhost/mysite/cache/%1

That's maybe the reason for your infinite loop. To resolve this, either make sure the htaccess rules are not applied to the sub-directories or use another directory for the cache.


Here is the solution for anyone else having this problem:

RewriteEngine on
RewriteRule ^.+$ - [L]
RewriteCond %{HTTP_COOKIE} ^.*user_id=(\d+).*$ [NC]
RewriteRule .* http://localhost/mysite/$1 [R=301,L]
RewriteRule .* http://localhost/mysite/guest [R=301,L]

Although I haven't tested the cookie part yet - I'm sure there will be many more problems there! But the rest I tested and it works! (it goes to guest and then does not go into infi-loop, yay!)

Have a great day! 8)