# NGINX configuration for load balancing of Node.JS Application Servers
#
# The configuration file should be saved to /etc/nginx/conf.d/nodejs-basic.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 more information on NGINX Plus, the commericial version of NGINX, 
# please see http://www.nginx.com/products/
#
# Tested with NGINX 1.11.3
#
# Sep 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 {
    # Use IP Hash for session persistence
    ip_hash;
 
    # List of Node.JS Application Servers
    server 192.168.33.11:8080;
    server 192.168.33.12:8080;
}
 
	 
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;

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

    # WebSocket configuration
    location /wstunnel/ {
        proxy_pass https://nodejs;
       	proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}
