...
Skip to main content
Print

How to Set Up Nginx as a Reverse Proxy

With Nginx as a reverse proxy you make an app that runs on an internal port, such as 3000, reachable via your own domain with HTTPS. Nginx forwards the traffic with proxy_pass. This way you do not need to open the port of your app and you run multiple apps on one server, each on its own domain.

Step 1: install Nginx

Do not have Nginx yet? Then first read How to Install Nginx on Ubuntu.

Step 2: create the configuration

nano /etc/nginx/sites-available/app.example.com
server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        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_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

The Upgrade and Connection lines make websockets work, which many modern apps use.

Step 3: enable the configuration

ln -s /etc/nginx/sites-available/app.example.com /etc/nginx/sites-enabled/
nginx -t
systemctl reload nginx

Step 4: add HTTPS

certbot --nginx -d app.example.com

Read more in How to Install a Free SSL Certificate With Certbot.

Common errors

  • 502 Bad Gateway: your app is not running or listens on a different port. Check this with ss -tulpn.
  • 504 Gateway Timeout: your app responds too slowly. Then increase proxy_read_timeout.

Related articles

Table of Contents