8

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!!!

BinaryGal
  • 91
  • 1
  • 1
  • 4

2 Answers2

8

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.

fuxia
  • 62,923
  • 6
  • 54
  • 62
metter
  • 1,434
  • 11
  • 22
  • Where can I look up information on how to tell it which subdirectories to apply to? Thank you. – BinaryGal Oct 20 '10 at 15:51
  • I finally found a web page with the answer: http://www.askapache.com/htaccess/mod_rewrite-tips-and-tricks.html#menu0-el14 The trick is to use a dash "-" thingy. Here is my solution that works: RewriteRule ^.+$ - [L] – BinaryGal Oct 20 '10 at 17:57
1

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)

BinaryGal
  • 91
  • 1
  • 1
  • 4
  • 3
    thought I'd add, if you want to redirect if user_id is NOT present, do this instead: `RewriteCond %{HTTP_COOKIE} !^.*user_id=(\d+).*$ [NC]` – Stephen Fuhry Jan 28 '12 at 16:23