views:

32

answers:

1

I've got two hostnames (e.g. www.site1.com and www.site2.com) mapped to the same apache virtual host. I'd like to redirect all traffic from site1.com over to site2.com, except for all POST requests from a particular folder. (That folder contains URLs which are used by older clients which are not capable of handling redirects on POST requests.)

Here's the rule I came up with. I'm a newbie to rewrite rules, so wanted to make sure I wasn't missing anything obvious.

RewriteCond %{HTTP_HOST} ^www.site1.com$
RewriteCond %{HTTP_METHOD} ^POST
RewriteCond %{REQUEST_URI} !^/dontredirectme/
RewriteRule /(.*) http://www.site2.com/$1 [R=301,L]

Is this a correct rule to use for this job? And if yes, are there any efficiency optimizations I should be considering?

+1  A: 

Your rule set looks relatively correct, but you need to modify your second RewriteCond a little to reflect your goal:

RewriteCond %{HTTP_METHOD} !^POST [OR]

This will allow you to redirect if the request type is not POST, or it is and the requested URI is not /dontredirectme/, which effectively results in a redirect for everything that isn't a POST request to /dontredirectme/.

Additionally, the input to the RewriteRule will not have a leading forward slash if you're defining it in a per-directory context (in a .htaccess file or in a <Directory> section). If you are defining it directly in the <VirtualHost> (a per-server context), then the input will have a leading slash, so your rule would be fine as-is.

As far as efficiency goes, rules defined in the server configuration have the benefit of only having to be parsed one time. On the other hand, a .htaccess file must be parsed for each request, a process which involves the additional (albeit small) overhead of reading the file and compiling the regular expressions.

If you really want to squeeze efficiency out of it, you could make the following changes:

RewriteCond %{HTTP_HOST}    =www.example.com
RewriteCond %{HTTP_METHOD} !=POST [NC,OR]
RewriteCond %{REQUEST_URI} !^/dontredirectme/
RewriteRule ^ http://www.example.net%{REQUEST_URI} [R=301,L]

I doubt the difference is really appreciable in all but the most extreme cases, but this removes two regular expressions in favour of a direct text comparison. Also, since you just want to redirect the request to the new host verbatim, you can "simplify" the regular expression involved in the RewriteRule and just use %{REQUEST_URI} directly in the replacement.

Tim Stone
great answer. exactly what I was looking for.
Justin Grant