Forum Moderators: phranque

Message Too Old, No Replies

mod rewrite infinite loop

mod_rewrite looping

         

bantunes

5:20 pm on Apr 7, 2009 (gmt 0)

10+ Year Member



Hello all.

I have a very specific need: to protect access to files in a directory on my server.

The things is:

user tries to access files in /libs and has no "foo" cookie present = I send a 401
user tries to access files in /libs and has a "foo" cookie set = I redirect to a CGI script that validates the cookies and either a) sends a 401 if the cookie is not valid or b) redirects users to file in /libs he wants to access if cookie is valid.

Problem is, when I do the redirect in the CGI the rule gets processed again and again... looping! How can I fix this?

Here is my code:


RewriteCond %{HTTP_COOKIE} !session
RewriteRule ^/libs/(.*)$ [forbidden,last]

RewriteCond %{REQUEST_URI} !^/cgi-bin/cookie-cutter\.cgi$
RewriteRule ^/libs/(.*)$ /cgi-bin/cookie-cutter.cgi?url=$1 [proxy]

Thank you for any replies!

jdMorgan

5:27 pm on Apr 7, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Make sure that the 'realm' of the cookie includes the URL to which the cgi script redirects, and that the script preserves the session.

A redirect is a server response to the client which says, "The resource you asked for has moved, ask for it again at this new URL." Therefore the current HTTP transaction is terminated, and the client must begin a new one using the new URL supplied in the server's previous redirect response.

So, because the client invokes a new HTTP transaction, your rules are going to be re-evaluated, and will do what you say, not necessarily what you want. ;)

Jim

bantunes

5:32 pm on Apr 7, 2009 (gmt 0)

10+ Year Member



Thanks, found the solution myself:

RewriteCond %{HTTP_COOKIE} !session
RewriteRule ^/libs/(.*)$ [forbidden,last]

RewriteCond %{ENV:REDIRECT_STATUS} !^$
RewriteRule ^/libs/(.*)$ /cgi-bin/cookie-cutter.cgi?url=$1 [proxy,last]

jdMorgan

5:42 pm on Apr 7, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Note that you can use just [F] in the first rule, as [L] is implicit with [F], and that in the second rule you should not have to proxy the request to the script unless it is hosted on a different server; If on the same server, then only [L] should be needed, or perhaps [PT,L]. If the script is separately-hosted, then a protocol and domain or IP address should be specified in the substitution URL, since a proxy request creates a new HTTP connection.

Jim

bantunes

5:46 pm on Apr 7, 2009 (gmt 0)

10+ Year Member




Many thanks for your help.