Skip to content

Nginx Configuration for Serving SPA with API Proxy and WebSocket Support

Description: This Nginx configuration serves a Single Page Application (SPA), proxies /api requests to a backend server, and supports WebSocket connections. It also includes SPA route handling, gzip compression, and fallback to index.html for unknown routes.

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

    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. listen 80; – Nginx listens on port 80 for HTTP traffic.
  2. server_name – Set your domain name here.
  3. root /var/www/spa; index index.html; – Serves the SPA files from the specified folder.
  4. SPA Route Handling – try_files $uri /index.html; ensures that client-side routes work.
  5. API Proxy (/api/) – Forwards requests to your backend server, supports HTTP and WebSocket upgrades.
  6. WebSocket (/ws/) – Ensures WebSocket connections are properly proxied.
  7. Gzip Compression – Optimizes delivery of static assets.
  8. Error Page Handling – Routes unknown paths to index.html to support SPA routing.

This setup works well for Vue, React, or Angular SPA projects that also need API endpoints and WebSocket connections.