Skip to content

Nginx Configuration for Serving SPA with API Proxy and WebSocket Supportand SSL

Description: This Nginx configuration serves a Single Page Application (SPA), proxies /api requests to a backend server, supports WebSocket connections, and secures the site with SSL using Let's Encrypt or a custom certificate.

nginx
server {
    listen 80;
    server_name your-domain.com;

    # Redirect HTTP to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name your-domain.com;

    # SSL configuration
    ssl_certificate /etc/ssl/certs/your-cert.crt;       # Path to SSL certificate
    ssl_certificate_key /etc/ssl/private/your-key.key;   # Path to SSL key
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    root /var/www/spa;
    index index.html;

    # Serve SPA routes
    location / {
        try_files $uri /index.html;
    }

    # Proxy /api requests to backend
    location /api/ {
        proxy_pass http://127.0.0.1:3000/;  # Change to your backend server
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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_set_header X-Forwarded-Proto $scheme;
    }

    # Optional: handle WebSocket connections
    location /ws/ {
        proxy_pass http://127.0.0.1:3000/;  # Backend WebSocket server
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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_set_header X-Forwarded-Proto $scheme;
    }

    # Optional: gzip for SPA assets
    gzip on;
    gzip_types text/css application/javascript application/json image/svg+xml;
    gzip_min_length 256;

    # Error pages
    error_page 404 /index.html;
}

Explanation of Code:

  1. HTTP port 80 redirects all traffic to HTTPS.
  2. listen 443 ssl; enables HTTPS traffic.
  3. ssl_certificate and ssl_certificate_key point to your SSL cert and key.
  4. SPA serving, API proxy, and WebSocket support remain the same.
  5. Gzip compression and error handling are also retained for SPA routing.

This setup ensures secure access to your SPA with API and WebSocket support.