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