Nginx:如何重写User-Agent如果是空的

如何在空的时候设置User-Agent头? (例如,HTTP / 1.0)

这是我到目前为止所尝试的:

set $ua $http_user_agent; if ($http_user_agent = "") //also tried = false { set $ua "Fixing-Empty-User-Agent"; proxy_pass http://$host$request_uri; } proxy_connect_timeout 2; proxy_send_timeout 10; proxy_read_timeout 10; proxy_set_header User-Agent: $ua; 

你的configuration是正确的,像这里的魅力一样(CentOS 7,nginx 1.6.1)。

如果你检查你的error_log文件,你可能会看到这样的错误:

2014/09/10 09:35:45 [error] 5786#0:* 3没有定义parsing器来parsingexample.com,client:1.2.3.4,server:example.com,request:“GET / HTTP / 1.1”,主机:“example.com”

在这种情况下,将parsing器添加到nginx的位置子句。 例如:

 resolver 8.8.8.8; 

这是access_log中的结果:

1.2.3.4 – – [10 / Sep / 2014:09:37:40 -0400]“GET / HTTP / 1.0”200 2155“ – ”“:Fixing-Empty-User-Agent”“ – ”

最好避免if指令。 您可以改为使用地图来填充$ua ,具体取决于接收到的User-Agent头是否缺失或为空:

 http { ... map $http_user_agent $ua { '' "Fixing-Empty-User-Agent"; default $http_user_agent; } ... server { ... location xx { proxy_pass yy; proxy_set_header User-Agent: $ua; ... } ... } } }