
我在一個網域上有很多服務。例如:
- example.com/data_first/
- example.com/data_home/
- example.com/data_test/
和別的
對於所有配置了相同操作的服務,coocie auth 在 NGINX 配置中包含 20 多行。
但是,我想將其概括為一個包含的配置,以便輕鬆添加新服務。
我在配置下一個指令中寫入:
map $request_uri $xService{
~^/data_(?<fp>(first|home|test))/ data_$fp;
default 0;
}
server{
...
if ($xService){
include xService.conf;
}
...
}
我的 xService.conf 包含指令:
location /$xService/ {
add_header X-Pass-Return $xService;
... other directives include if, rewrite, proxy_pass
}
但我不能在 if 指令中使用 location 指令。是否可以在不列出所有可能的位置選項的情況下解決這樣的問題?
例如。我使用下一個配置:
location ^~ /data_first/{
set $xService data_first;
include xService.conf;
}
和其他位置,但我不需要為任何服務 URI 編寫位置。
答案1
為什麼要使用映射和 if 語句?
server {
server_name example.com;
...
location /data_first {
include snippets/YOUR_COMMON_CONFIG;
# add the stuff specific to /data_first here...
add_header X-Pass-Return /data_first/;
...
}
location /data_home {
include snippets/YOUR_COMMON_CONFIG;
# add the stuff specific to /data_home here...
add_header X-Pass-Return /data_home/;
...
}
location /data_test {
include snippets/YOUR_COMMON_CONFIG;
# add the stuff specific to /data_test here...
add_header X-Pass-Return /data_test/;
...
}
}
答案2
可能只使用簡單的一個:
location ~ ^/(data_\w+)/ {
add_header X-Pass-Return /$1/;
...
}