How to use nginx to direct traffic to two different ports on the same device?

Solution 1:

This minimal config should provide public endpoints:

  1. http://example.com/* => https://example.com/*
  2. https://example.com/stream => http://1.2.3.4:5001/
  3. https://example.com/* => https://1.2.3.4:5000/
# redirect to HTTPS
server {
  listen      80;
  listen [::]:80;
  server_name example.com
              www.example.com;

  return 301 https://example.com$request_uri;
}

server {
  listen      443 ssl http2;
  listen [::]:443 ssl http2;
  server_name example.com
              www.example.com;
  ssl_certificate     /etc/nginx/ssl/server.cer;
  ssl_certificate_key /etc/nginx/ssl/server.key;

  location /stream {
    proxy_pass http://1.2.3.4:5001/;  # HTTP
  }

  # fallback location
  location / {
    proxy_pass https://1.2.3.4:5000/; # HTTPS
  }
}