# NGINX Plus configuration for enhanced load balancing of Node.JS
# Application Servers
#
# The configuration file should be saved to /etc/nginx/conf.d/nodejs-enhanced.conf.
# In the main /etc/nginx/nginx.conf file ensure that the following line is 
# present in the http {...} block:
# include /etc/nginx/conf.d/*.conf;
#
# For more information, see http://nginx.org/r/include, and the 'Using NGINX
# and NGINX Plus to Load Balance Node.JS Application Servers' deployment guide at
# http://www.nginx.com/
#
# For support please see http://www.nginx.com/support/
#
# Tested with NGINX Plus R10
#
# Sept 26, 2016
# Version 1.0

proxy_cache_path /tmp/NGINX_cache/ keys_zone=backcache:10m;
 
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
  
upstream nodejs {
    # Health-monitored upstream groups must have a zone defined
    zone nodejs 64k;
 
    # List of Node.JS Application Servers
    server 192.168.33.11:8080 slow_start=30s;
    server 192.168.33.12:8080 slow_start=30s;

    # Session Persistence using sticky cookie, if necessary
    sticky cookie srv_id expires=1h domain=.example.com path=/;
}

match nodejs_check {
    status 200;
    header Content-Type ~ "text/html";
    body ~ "Hello world";
}

server {
    listen 80;
    server_name example.com;
 
    # Redirect all HTTP to HTTPS  
    location / {
        return 301 https://$server_name$request_uri;
    }
}
 
server {
    listen 443 ssl http2;
    server_name example.com;

    # Required for NGINX Plus to provide extended status information.
    status_zone nodejs;
 
    ssl_certificate     /etc/nginx/ssl/certificate-name;
    ssl_certificate_key  /etc/nginx/ssl/private-key;
    ssl_session_cache    shared:SSL:1m;
    ssl_prefer_server_ciphers  on;
 
    # Return a 302 Redirect to the /webapp/ directory
    # when user requests /
    location = / {
        return 302 /webapp/;
    }
 
    # A location block is needed per URI group
    location /webapp/ {
        proxy_pass http://nodejs;
        proxy_cache backcache;
 
        # Set up active health checks.  If the server responds with a
        # status other than 2xx or 3xx, the health check will fail
        # and the server will be marked down.
	health_check match=nodejs_check;
    }
 
    # WebSocket configuration
    location /wstunnel/ {
        proxy_pass http://nodejs;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }

    # location block for secured access to the upstream_conf handler
    location /upstream_conf {
        upstream_conf;

        allow 127.0.0.1; # permit access from localhost
        deny all;        # deny access from everywhere else
    }
}

