Forum Moderators: phranque

Message Too Old, No Replies

Mod_rewrite help to redirect to a virtual subdirectory

Redirecting based on user agent

         

dan121

1:43 pm on Aug 2, 2005 (gmt 0)

10+ Year Member



I have these two rewrite rules that seem to do exactly what I want: change requests for files in a subdirectory into a file name and a variable, so
http://www.example.com/subdirectory/filename -> http://www.example.com/filename?subdirectory

RewriteRule ^subdirectory$ subdirectory$1/ [R] #add trailing slash
RewriteRule ^subdirectory/(.*) /$1?subdirectory [NC]

I would also like to automatically send certain user agents to this virtual subdirectory. Something like this:

RewriteCond %{HTTP_USER_AGENT} ^useragent1 [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^useragent2 [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^useragent3 [NC]
RewriteRule ^(.*)$ /subdirectory/$1 [L]

Of course, this doesn't work, it results in a loop that errors out.

Help!

jdMorgan

2:14 pm on Aug 2, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You'll need to add logic so that once a user-agent is 'sent' to that subdirectory, no further rewrites are performed by your code.

...
RewriteCond %{HTTP_USER_AGENT} ^useragent3 [NC]
[i]RewriteCond %{REQUEST_URI} !^/subdirectory/[/i]
RewriteRule ^(.*)$ /subdirectory/$1 [L]

Be aware that after any rewrite, the server configuration files (httpd.conf and all .htaccess files in the new URL-path) must be re-run to check for access controls (password-protected directories) and further rewrites that apply to the new URL-path. For this reason, mod_rewrite in .htaccess appears to be recursive, and therefore steps must be taken to prevent the looping you experienced.

Jim

dan121

3:06 pm on Aug 2, 2005 (gmt 0)

10+ Year Member



That makes sense, but for some reason it isn't working.

When I add in:

RewriteCond %{HTTP_USER_AGENT} ^useragent3 [NC]
RewriteCond %{REQUEST_URI}!^/subdirectory/
RewriteRule ^(.*)$ /subdirectory/$1 [L]

And then request a page using "useragent3", my browser just hangs. I'm watching the HTTP headers and there's no network traffic (like in a redirect loop) and I never get a server error, the page just sits there like it's loading, but nothing ever comes up. When I comment out the three lines above, things return to normal.