NginxReverse ProxyProxy6 min read

Configure reverse proxy with Nginx

Configure Nginx as a reverse proxy to route traffic to internal applications by port or domain.


A reverse proxy forwards client requests to backend applications (Node.js, Python, etc.) running on internal ports. Nginx handles SSL, caching and static files.

Prerequisites

  • Nginx installed (see "Install and configure Nginx" guide)
  • A backend application running on a local port (e.g., port 3000)

Step 1 — Create the Nginx configuration

bash
sudo nano /etc/nginx/sites-available/myapp

Basic reverse proxy:

nginx
server {
    listen 80;
    server_name mydomain.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
        proxy_cache_bypass $http_upgrade;
    }
}

Step 2 — Enable the site

bash
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Step 3 — Add SSL with Certbot

bash
sudo certbot --nginx -d mydomain.com

Advanced: Multiple applications

nginx
server {
    listen 80;
    server_name mydomain.com;

    location /api {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location /admin {
        proxy_pass http://127.0.0.1:4000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location / {
        root /var/www/mydomain.com/html;
        try_files $uri $uri/ /index.html;
    }
}

WebSocket support

The Upgrade and Connection headers in the basic config already support WebSockets. For dedicated WebSocket paths:

nginx
location /ws {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400;
}

Performance tuning

nginx
proxy_buffering on;
proxy_buffer_size 16k;
proxy_buffers 4 32k;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

Tip

Always test configuration before reloading: sudo nginx -t. A syntax error in the config will prevent Nginx from reloading and could cause downtime.


Was this guide helpful?