Friday, February 17, 2012

Reverse Proxy With Nginx

As we know Nginx is event driven and uses persistent connections which makes it faster as compare to other Web / Proxy Servers. So, here's the simple example for setting up reverse proxy with NginX with some caching options:

Install Nginx

Create a file in /etc/nginx/conf.d/whatever.conf and enter following contents:

server {
    listen       80;
    server_name ; # Server Names for which you want to make this server proxy

    access_log  off;
    error_log off;

    # proxy to Apache 2 and mod_python
    location / {
        proxy_pass         http://Backend_Server_IP:80/;
        proxy_redirect     off;

        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_max_temp_file_size 0;

        proxy_connect_timeout      60;
        proxy_send_timeout         60;
        proxy_read_timeout         60;

        proxy_buffer_size          4k;
        proxy_buffers              4 32k;
        proxy_busy_buffers_size    64k;
        proxy_temp_file_write_size 64k;

For Caching contents create a file /etc/nginx/conf.d/cache.conf and enter following contents:

## Size Limits
  client_body_buffer_size     128K;
  client_header_buffer_size   1M;
  client_max_body_size          1M;
  large_client_header_buffers 8 8k;

 ## Timeouts
  client_body_timeout   60;
  client_header_timeout 60;
  expires               24h;
  keepalive_timeout     60 60;
  send_timeout          60;

 ## General Options
  ignore_invalid_headers   on;
  keepalive_requests      100;
  limit_zone gulag $binary_remote_addr 5m;
  recursive_error_pages    on;
  sendfile                 on;
  server_name_in_redirect off;
  server_tokens           off;

 ## TCP options
  tcp_nodelay on;
  tcp_nopush  on;

 ## Compression
  gzip              on;
  gzip_buffers      16 8k;
  gzip_comp_level   6;
  gzip_http_version 1.0;
  gzip_min_length   0;
  gzip_types        text/plain text/css image/x-icon application/x-perl application/x-httpd-cgi;
  gzip_vary         on;

 ## Log Format
  log_format  main  '$remote_addr $host $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" "$http_user_agent" '
                    '"$gzip_ratio" "$http_x_forwarded_for"';

This cache.conf will be used by default for all your VHOSTS content caching, so you can manage accordingly :)

Start nginx service : service nginx start

Please correct if find somewhere mis-spelled or incorrect!!!

No comments: