How would I write an if - elseif - elseif conditional block in an .htaccess file?

≯℡__Kan透↙ 提交于 2019-12-21 20:44:49

问题


This is what I want to accomplish in pseudocode:

if server.host equals 'productionsite.com' then
  RewriteBase /
else if server.host equals 'stagingsite.com' then
  RewriteBase /staging/mysite
else if server.host equals 'localhost' or server.host equals '127.0.0.1' then
  Rewrite /dev/mysite

However, this is what I actually have so far which doesn't seem to work as I expect:

RewriteCond %{HTTP_HOST} =productionsite.com
RewriteBase /

RewriteCond %{HTTP_HOST} =stagingsite.com
RewriteBase /staging/mysite

RewriteCond %{HTTP_HOST} =localhost
RewriteBase /dev/mysite

I appreciate any help I can get in advance.


回答1:


Not an answer per-se (started out as a comment), but may help you a bit:

Your approach doesn't work because the RewriteBase isn't affected by RewriteCond directives. A RewriteCond can only be followed by another RewriteCond or a RewriteRule. RewriteBase is an entirely different beast: I don't think that a conditional RewriteBase is possible; I have the vague feeling that it's processed at startup, so can't be changed dynamically (but I may be very wrong about this). Google has a number of hits for "conditional rewritebase", you may look through those, but they seem largely negative.

Toying with IfDefine to achieve a similar effect would be worth a shot.

Alternatively, you could try doing it with RewriteRules and environmental variables:

 RewriteBase /

 RewriteCond %{HTTP_HOST} =stagingsite.com
 RewriteRule ^ - [E=FRB:/staging/mysite]

 RewriteCond %{HTTP_HOST} =localhost
 RewriteRule ^ - [E=FRB:/dev/mysite]

And then prepend each rewrite path with the FRB environmental variable, like

 RewriteRule ^home$ %{ENV:FRB}/index.php

But this is just an untested theory.




回答2:


For me the solution from https://snipt.net/beat/htaccess-different-bases-subfolders-in-developmentproduction/ worked

RewriteCond %{HTTP_HOST} !^localhost$
RewriteRule . - [E=REWRITEBASE:/prod/]

RewriteCond %{HTTP_HOST} ^localhost$
RewriteRule . - [E=REWRITEBASE:/dev/]


来源:https://stackoverflow.com/questions/7813554/how-would-i-write-an-if-elseif-elseif-conditional-block-in-an-htaccess-file

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