How to Use Nginx as a Reverse Proxy: A Practical Configuration Guide

Nginx is the go-to tool for reverse proxying. It accepts client requests, forwards them to backend servers (like Node.js or Python apps), and returns the responses. This setup boosts performance, adds a security layer, and centralizes SSL handling.

Before you begin, install Nginx and ensure you have root or sudo access. Configurations typically live in /etc/nginx/sites-available/. Let’s walk through the essentials.

Article illustration

1. Basic Reverse Proxy Configuration

The simplest setup proxies all requests to a local backend. Add this to your server block:

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

After editing, run nginx -t to test and systemctl reload nginx to apply changes.

2. Forward Client Headers

Backends need the original client information. Use these headers so your app sees the real visitor IP and protocol:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;

This is essential for accurate logging and for apps that generate absolute URLs.

3. Load Balancing with Upstreams

upstream backend {
    server 10.0.0.1;
    server 10.0.0.2;
}
server {
    location / {
        proxy_pass http://backend;
    }
}

Nginx distributes requests across all servers in the upstream group. You can also add weight or max_fails parameters for more control.

4. WebSocket and Docker Considerations

If your app uses WebSockets, add proxy_set_header Upgrade $http_upgrade; and Connection "upgrade"; to avoid broken connections. For Docker, set proxy_pass http://localhost:8080 and map container ports correctly.

Conclusion

Nginx reverse proxying is straightforward once you understand the basics. Start with a simple proxy, add headers, then expand to load balancing and WebSockets as your app grows.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *