解决Nginx不支持if块嵌套proxy_set_header
有时候我们想在Nginx的配置上加上一些判断,假如条件为真,那么就怎么样。比如:1
2
3
4
5
6
7location / {
if ($http_referer ~ "http[s]?\:\/\/\w*\.?keepmoving.*") {
# do something
# proxy_set_header Host "test.host";
}
proxy_pass http://your.service;
}
假如referer来自keepmoving.ren
的域名,那么就加一个头部Host值为test.host给到上游服务器。
但你会发现解开上面的注释后,执行nginx -t
会报错:1
nginx: [emerg] "proxy_set_header" directive is not allowed here in /usr/local/etc/nginx/test.conf:10
原因是Nginx不支持在if块里面设置proxy_set_header。
那我们可以换一种做法,采用变量的方式赋值:1
2
3
4
5
6
7
8location / {
set $xhost $host;
if ($http_referer ~ "http[s]?\:\/\/\w*\.?keepmoving.*") {
set $xhost "test.host";
}
proxy_set_header Host $xhost;
proxy_pass http://your.service;
}
另外我们也可以采用map的方式来配置,等待后续补充。
参考
proxy - nginx: Why I can’t put proxy_set_header inside an if clause? - Server Fault
- 本文链接:https://keepmoving.ren/nginx/proxy-set-header-with-if/
- 版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 CN 许可协议。转载请注明出处!