傅令江的光影色彩世界
nginx中的if和else语法,变通下
2021-10-25 傅令江

nginx支持if语法,语法和平常的代码格式差不多:

if ($xxx = xxx) {
    xxx
}


nginx虽然有if,但是却不支持else,如果想要构造else语法,可以使用下面的这个“小诀窍”:


server {
    server_name *.maqian.io;
    listen 80;
    
    location / {
        set $is_matched 0;
        if ($host = a.maqian.io) {
            proxy_pass https://127.0.0.1:1001/;
            set $is_matched 1;
        }
        
        if ($host = b.maqian.io) {
            proxy_pass https://127.0.0.1:1002/;
            set $is_matched 1;
        }
        # 没有匹配到,跳转到默认页面
        if ($is_matched = 0) {
            proxy_pass https://127.0.0.1;
        }
        
        # xxx
        # xxx
        # xxx
    }
}


1.当访问的文件和目录不存在时,重定向到某个html文件
if( !-e $request_filename )
{
    rewrite ^/(.*)$ index.html last;
}




#这个不会自动index.html
if (-e $document_root/static$request_uri) {
 rewrite ^/(.*)$ /static/$1 break;
 break;
}

#这个会自动index.html
if (-e "${document_root}/static${uri}") {
 rewrite ^/(.*)$ /static/$uri break;
}
if (-e $request_filename) {
 break;
}

#这个设置index
set $static "/static";
try_files $static$uri $static$uri/index.html /index.php;



发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容