Nginx: How to rewrite User-Agent if empty

nginx

How can I set an User-Agent header when empty? (Eg, HTTP/1.0)

This is what I tried so far:

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;

Best Answer

Your configuration is correct and works like a charm here (CentOS 7, nginx 1.6.1).

If you check your error_log file, you'll probably see an error like this:

2014/09/10 09:35:45 [error] 5786#0: *3 no resolver defined to resolve example.com, client: 1.2.3.4, server: example.com, request: "GET / HTTP/1.1", host: "example.com"

In that case, add a resolver to nginx's location clause. For instace:

resolver 8.8.8.8;

And this is the result in access_log:

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