views:

141

answers:

1

Hi! I'm trying to get my head around RewriteCond, and want to rewrite any requests either to a static html page (if it exists), or to a specific index.php (so long as the requested file doesn't exist).

To illustrate the logic:

if HTTP_HOST is '(www\.)?mydomain.com'
    if file exists: "/default/static/{REQUEST_URI}.html", then
        rewrite .* to /default/static/{REQUEST_URI}.html
    else if file exists: {REQUEST_FILENAME}, then
        do not rewrite
    else
        rewrite .* to /default/index.php

I don't seem to have much trouble doing it when I don't need to test for the HTTP_HOST. Ultimately, this one .htaccess file will be handling requests for several domains.

I know I could get around this with vhosts, but I'd like to figure out how to do it this way.

I'm not too familiar with some of the other flags, will any of them be of use here (like chain|C, next|N or skip|S)?

Thanks in advance!


UPDATE: I've managed to do it, but would appreciate alternatives:

RewriteCond %{HTTP_HOST} ^(domainA|domainB)\..* [NC]
RewriteCond %{DOCUMENT_ROOT}/%1/static/%{REQUEST_URI}.html -f
RewriteRule (.*)? /%1/static/$1.html [NC,L]

RewriteCond %{HTTP_HOST} ^(domainA|domainB)\..* [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* /%1/index.php [L,QSA]

UPDATE #2: With help from Gumbo's answer, came up with another. I like that this would would require less maintenance in the case of added domains. (Thanks Gumbo!)

Are there any reasons why I shouldn't set ENV variables?

RewriteCond %{HTTP_HOST} ^(domainA|domainB)\..*$ [NC]
RewriteRule ^ - [E=APP:%1]

RewriteCond %{DOCUMENT_ROOT}/%{ENV:APP}/static/%{REQUEST_URI}.html -f       
RewriteRule (.*)? /%{ENV:APP}/static/$1.html [NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* /%{ENV:APP}/index.php [L,QSA]
+1  A: 

I would probably do it like this:

RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$
RewriteRule ^ - [S=2]

RewriteCond %{DOCUMENT_ROOT}/default/static%{REQUEST_URI}.html -f
RewriteRule !^default/static/ default/static%{REQUEST_URI}.html [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^default/static/ default/index.php [L]

This is similar to your updated example. Except that the first rule will skip the following two rules if the host is not appropriate. And the RewriteRule patterns exclude any path that starts with /default/static/. But your rules are already pretty good.

Gumbo
Thanks! While I was aware of it, I didn't know the syntax of the no-rewrite rule. This gave me the idea for another solution that turns out to be exactly what I wanted (updated the original post). Thanks again!
hlissner