Using variables in Nginx location rules

前端 未结 4 506
自闭症患者
自闭症患者 2020-12-12 17:54

In Nginx, I\'m trying to define a variable which allows me to configure a sub-folder for all my location blocks. I did this:

set $folder \'/test\';

location         


        
4条回答
  •  暖寄归人
    2020-12-12 18:35

    This is many years late but since I found the solution I'll post it here. By using maps it is possible to do what was asked:

    map $http_host $variable_name {
        hostnames;
    
        default       /ap/;
        example.com   /api/;
        *.example.org /whatever/;
    }
    
    server {
        location $variable_name/test {
            proxy_pass $auth_proxy;
        }
    }
    

    If you need to share the same endpoint across multiple servers, you can also reduce the cost by simply defaulting the value:

    map "" $variable_name {
        default       /test/;
    }
    

    Map can be used to initialise a variable based on the content of a string and can be used inside http scope allowing variables to be global and sharable across servers.

提交回复
热议问题