有时候我们想在Nginx的配置上加上一些判断,假如条件为真,那么就怎么样。比如:

1
2
3
4
5
6
7
location / {
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
8
location / {
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