Proxying with Nginx

nginx logo

Today, something refer to Nginx and proxy rules. The tips showed bellow aren’t a advanced rules but should be valid for 80% of all cases that we should want to us.

server {
  listen   8008;
  server_name server.net;
  access_log  /var/log/nginx/server.net.access.log;

  location /reflector/mcast {
    proxy_pass        http://93.37.29.30:80;
    include /etc/nginx/include-enabled/proxy_settings.conf;
    # Other settings related to proxy: headers, timeouts ...
    rewrite  ^/reflector/mcast/8$  http://93.37.29.30:80/video.php?channel=8 redirect;
    rewrite  ^/reflector/mcast/12$  /video.php?channel=12  break;
  }
  ...
}

The /etc/nginx/include-enabled/proxy_settings.conf would be something like this:

proxy_set_header  X-Real-IP  $remote_addr;
proxy_set_header  X-Forwarded-For  $remote_addr;
proxy_read_timeout 300;

The first rewrite rule defines a 302 redirection behavior. The server respond to client a 302 response refer to http://93.37.29.30:80/video.php?channel=8. The second one, respond a 20X response. Petition will be rewrite to /video.php?… and it’ll be delegate to proxy_pass module. In this case, the server implement a reverse proxy behavior.
Observe next items:

  • All petitions like /videos/ are proxified to http://10.13.30.26:8004/videos/:
    location /videos/ {
      proxy_pass        http://10.13.30.26:8004;
      include /etc/nginx/include-enabled/proxy_settings.conf;
    }
  • All petitions like /media/video.mpeg are proxified to http://10.14.20.41:8004/videos/video.mpeg:
    location /media/ {
      proxy_pass        http://10.14.20.41:8004/;
      include /etc/nginx/include-enabled/proxy_settings.conf;
      rewrite  ^/media/(.*)$ /videos/$1  break;
    }
  • All petitions like /media/8 are proxified to http://10.14.20.42:8004/?video=8:
    location /media/ {
      proxy_pass        http://10.14.20.42:8004/;
      include /etc/nginx/include-enabled/proxy_settings.conf;
      rewrite  ^/media/(.*)$ /?video=$1  break;
    }

Finally, next rule uses $arg_ special var to refer the get parameters in the URI. In this case, this server expect URLs like “/play?mo=video.mpeg” and it’ll try to serve video.mpeg storaged on /var/www.

location /play {
  root /var/www/;
  rewrite ^/play /$arg_mo redirect;
}

Enjoy it!.

Advertisements