Simulating a 2-level If-Else using RewriteCond

走远了吗. 提交于 2019-12-21 17:06:22

问题


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:


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.



来源:https://stackoverflow.com/questions/2833004/simulating-a-2-level-if-else-using-rewritecond

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!