大网数据广告活动
服务器运维问答

nginx set variable in location

· 52CE 我爱测

I am trying to optimize my nginx configs, so it would be possible to set one variable, and all location paths would update automatically. I have four lines in question: server_name php.domain.com; root /srv/web/vhosts/php/web; er…

问题原文

原帖链接 · Bogdan Kuštan · CC BY-SA 3.0

I am trying to optimize my nginx configs, so it would be possible to set one variable, and all location paths would update automatically. I have four lines in question:

server_name php.domain.com;
root /srv/web/vhosts/php/web;
error_log /srv/web/vhosts/php/logs/error.log;
access_log /srv/web/vhosts/php/logs/access.log;

What I would like to achieve is to set one variable (in this case 'php') and include it to config.

set $variable "php";
server_name $variable.domain.com;
root /srv/web/vhosts/$variable/web;
error_log /srv/web/vhosts/$variable/logs/error.log;
access_log /srv/web/vhosts/$variable/logs/access.log;

However it seams that nginx ignores variables in this config. Am I doing something wrong or it is not possible to use variable in location paths?

社区高分解答

原帖链接 · gruentee · CC BY-SA 4.0

You can use variables declared via map. This Stackoverflow answer discusses using custom variables in the expression part of location blocks:

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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2014-11-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。