# Define "upstream" servers here, i.e. those servers that NGINX
# can proxy requests to and from
upstream snap-thing-services {
  server 127.0.0.1:3000;
}

# This server listens on port 80, and redirects incoming requests to HTTPS
server {
  listen 80 default_server;
  listen [::]:80 default_server ipv6only=on;
  server_name $host;
  access_log /var/log/nginx/access.log;

  location /api/v1/ {
    return 403 "Use HTTPS instead of HTTP for API requests";
  }

  location / {
    return 301 https://$host$request_uri;
  }
}

server {
  listen 443 ssl;
  server_name $host;
  ssl_certificate      /etc/ssl/certs/snap-thing-services.crt;
  ssl_certificate_key  /etc/ssl/private/snap-thing-services.key;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

  # Direct the browser to enforce the use of HTTPS, even if the user
  # specifies HTTP as the protocol (see https://www.owasp.org/index.php/HTTP_Strict_Transport_Security)
  add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";

  # Ensure that content cannot be embedded in a frame on another web site
  add_header X-Frame-Options SAMEORIGIN;

  # Ensure that the Internet Explorer content sniffer is disabled
  add_header X-Content-Type-Options nosniff;

  # Force XSS protection and prevent browser from rendering pages if a potential XSS
  # reflection attack is detected
  add_header X-XSS-Protection "1; mode=block";

  # Incoming requests matching /api/v1 are proxied to the
  # `snap-thing-services` upstream
  location /api/v1/ {
    root /api/v1;
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_pass http://snap-thing-services;
  }

  # Incoming requests matching / are proxied to the
  # `snap-thing-services` upstream (i.e. for UI stuff))
  location / {
    # Proxy to upstream site snap-thing-services
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_pass http://snap-thing-services;

    # Also proxy websockets
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
}

