How to if/else statement with nginx conf?

is it possible to do something like this with nginx?

if ( $http_user_agent = "wget" ){
   server {
      listen      192.0.2.11:1111;
      root        /website1/;
      server_name website1.example www.website1.example;
else 

   server {
      listen      192.0.2.22:22222;
      root        /website2/;
      server_name example2.example www.website2.example;
}

Solution 1:

The Nginx rewrite module do have if directive (see the linked documentation for examples), but not else. The equivalent for else would be all that isn't modified with an if.

You can use if inside a server { } but not the other way around. You wouldn't even have the condition compared in your if before a request that already needs the server. There, you could only serve content when user agent is (or isn't) wget.

Also notice that you shouldn't use if inside location as it may not work as desired (see If Is Evil).

Solution 2:

In the form given it will not work: testing the HTTP User-Agent implies, that the request was already received. That is only possible if some server block was already defined. Do you really want to start new servers depending on the User-Agent string of a request you received somewhere else?

If you just want to serve different content, redirect to different paths, etc. depending on parts of the request like the User-Agent, that is possible, e.g. with http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

Solution 3:

Here's how I would do what I think you're looking for. I realize this is years old, but I was looking to do something similar and hope this helps someone in the future.

map $http_user_agent  $user_agent {
    default all;
    wget    wget;
}

server {
  listen 123;
  location / {
    proxy_pass http://$user_agent;
  }
}

upstream wget {
    server 127.0.0.1:1111;
}

upstream all {
    server 127.0.0.1:22222;
}

server {
    listen      127.0.0.1:1111;
    root        /website1/;
    server_name example.com www.example.com;
}

server {
    listen      127.0.0.1:22222;
    root        /website2/;
    server_name example2.com www.example2.com;
}