3

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;
1
  • Why do you need to fix?
    – Alexey Ten
    Sep 10, 2014 at 13:02

2 Answers 2

2

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" "-"

1
  • You are right - I had my error.log open but didn't bother reading it, I was sure that the error was still there (an empty user agent causes a 500 error, while this was a 502 one). Thank you! :)
    – cedivad
    Sep 10, 2014 at 15:08
0

It is better to avoid the if directive. You can instead use a map to populate $ua based on whether the received User-Agent header is missing or empty:

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;
            ...
         }
      ...
      }
   }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .