Almost every application you use runs behind a reverse proxy, and in most cases that proxy is Nginx. The application itself listens on a port on a private network, or on localhost, and never talks to the internet directly. Nginx sits in front of it, receives requests from browsers, forwards them to the application, and returns the application’s response as its own. This arrangement is simple to describe and surprisingly easy to get wrong in the details, which is why this tutorial works through it step by step.
By the end you will have a working reverse proxy for a real application, with the forwarded headers your application needs, HTTPS termination with a TLS certificate, WebSocket support for live features, and the timeout and buffering settings that keep long requests alive. Every directive is explained as it appears, and the common mistakes are flagged where they actually happen, so you can recognize them in your own configuration instead of learning about them from an error log at midnight.
What a Reverse Proxy Is and When to Use One
A reverse proxy is a server that receives requests on behalf of one or more backend servers and forwards each request to the right backend. The client only ever talks to the proxy, and never learns where the application actually runs. This is the reverse of a forward proxy, which sits beside the client and forwards its requests outward. The distinction matters because the two solve different problems: a forward proxy controls what clients can reach, while a reverse proxy controls how the outside world reaches your application.
There are four reasons teams put Nginx in front of an application. The first is TLS termination. Nginx handles the certificate and the encryption, and the application receives plain HTTP on a trusted local network, which means the application code never has to manage certificates. The second is a single public entry point for many applications. One Nginx server can route requests for different domains or paths to different backends, so ten applications can share one public address. The third is protection. The application binds to localhost, so only Nginx can reach it, and Nginx can add rate limiting, request size limits, and security headers before traffic ever touches application code. The fourth is operational flexibility: you can restart, replace, or scale the backend without changing anything the client sees, because the public address and the TLS certificate belong to Nginx.
Before writing any configuration, confirm that Nginx is installed and running. On a Debian or Ubuntu system the official Nginx packages are the recommended source, and the service is managed with systemd. Check the version and the running state first, because a proxy configuration cannot be tested against a server that is not running.
nginx -v
sudo systemctl status nginx
sudo nginx -t
The nginx -t command tests the configuration files for syntax errors without reloading the server, and it is the command you should run before every reload. Make it a habit now, because a failed reload leaves the old configuration running, while a successful test followed by a reload applies your change. Our Linux systemd tutorial covers service management in more depth, including how to read service logs when Nginx fails to start.
Your First proxy_pass Configuration
The proxy_pass directive is the core of the whole setup. Placed inside a location block, it tells Nginx where to forward requests that match that location. The official example configuration from the ngx_http_proxy_module documentation is only a few lines long, and it is worth starting from exactly that shape before adding anything else.
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
That example lives inside a server block, which is the unit that handles one domain. A complete minimal server block for an application listening on port 3000 on the same machine looks like this. The application can be anything that speaks HTTP: a Node.js service, a Python web framework, a Go binary, or a container with a published port.
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
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;
}
}
Here is what happens when a browser requests this site. Nginx picks the server block whose server_name matches the Host header the browser sent. It then picks the location with the longest matching prefix, which for a request to the site root is location /. The proxy_pass directive opens a connection to the backend, sends the request, and streams the response back to the browser. If the backend is not running, Nginx answers with a 502 Bad Gateway error, which is the single most common error you will see while setting up a proxy, and it almost always means the backend address or port is wrong or the application has not started.
Where the file goes depends on how Nginx was installed. The official Nginx packages read every file ending in .conf in /etc/nginx/conf.d/, so a file such as /etc/nginx/conf.d/app.conf is loaded automatically. Debian and Ubuntu packages use the sites-available and sites-enabled directories instead, so you create the file in sites-available and link it into sites-enabled. Either way, test the configuration and reload after every change.
sudo nginx -t
sudo systemctl reload nginx
curl -I http://app.example.com/
The curl command confirms the proxy answers. A 200 response with your application’s headers means the proxy works. A 502 means the backend is unreachable, and the Nginx error log will say exactly why, usually a connection refused error pointing at the address in your proxy_pass line.
The Trailing Slash Rule and URI Rewriting
The most common Nginx proxy surprise is the trailing slash rule, and it comes down to one question: does your proxy_pass directive contain a URI? A URI is anything after the host and port, even a single slash. When there is no URI, the request path is passed to the backend unchanged. When there is a URI, the part of the request path that matched the location is replaced by that URI. The ngx_http_proxy_module documentation states this rule, and its own example is location /name/ with proxy_pass http://127.0.0.1/remote/, where a request for /name/page reaches the backend as /remote/page.
The table below shows the rule in action for a location of /api/ and a request for /api/users. Read each row carefully, because the difference between two of them is a single character.
| Location | proxy_pass | Request | Backend receives |
|---|---|---|---|
/api/ |
http://127.0.0.1:3000 |
/api/users |
/api/users |
/api/ |
http://127.0.0.1:3000/ |
/api/users |
/users |
/api/ |
http://127.0.0.1:3000/v2/ |
/api/users |
/v2/users |
/api/ |
http://127.0.0.1:3000/v2 |
/api/users |
/v2users |
The first row has no URI, so the path passes through unchanged. The second row has a URI of a single slash, so the matched /api/ prefix is replaced by / and the backend sees /users. The third row replaces the prefix with /v2/, which is how you expose a backend’s new API version at an old path. The fourth row is the trap: the URI is /v2 with no trailing slash, so the replacement produces /v2users, and most frameworks answer that with a 404. Keep the slashes paired. If the location ends in a slash, the URI should end in one too, and if the location has no trailing slash, the URI should not have one either.
There are two more rules worth knowing. Inside a regular expression location, proxy_pass must not contain a URI at all, so Nginx cannot rewrite the path there. If you need rewriting in a regular expression location, use the rewrite directive before proxy_pass, or restructure the configuration to use prefix locations. Second, when the backend is named in a variable, Nginx resolves the name at request time rather than at startup, which changes how DNS failures behave. For most setups a literal address is simpler and easier to debug, so use a variable only when the backend address genuinely changes at runtime.
When a proxied application is split across paths, give each path its own location with its own proxy_pass. An application at the root and an API on /api/ is the most common split, and it is clearer as two locations than as one location with rewriting rules. Test each location separately with curl. Our Docker Compose tutorial shows how to run the backend services this kind of split configuration points at, including the port mappings that make the addresses line up.
Forwarded Headers: Host, Real IP and Scheme
By default, Nginx does not pass the client’s Host header to the backend, and it sends no information about the original visitor at all. The defaults in the proxy module are to send the Host as the name and port from the proxy_pass directive, and to send Connection: close. That means an application behind a minimal proxy sees every request as coming from 127.0.0.1 over plain HTTP, addressed to 127.0.0.1:3000, no matter which domain the visitor actually requested. Logs show one address, generated links point at the wrong host, and login redirects send users to an internal address that does not exist for them.
Four proxy_set_header lines fix this, and they belong in almost every proxy location you will ever write. Each one restores a piece of information the application needs to behave as if it were directly exposed to the internet.
| Header | Value | What it gives the application |
|---|---|---|
Host |
$host |
The host name the visitor requested |
X-Real-IP |
$remote_addr |
The visitor’s address as Nginx saw it |
X-Forwarded-For |
$proxy_add_x_forwarded_for |
The chain of addresses through every proxy |
X-Forwarded-Proto |
$scheme |
Whether the visitor used HTTP or HTTPS |
The Host header deserves a closer look. The value $host is the host name from the request, falling back to the server name when the client sent no Host header. The documentation recommends it over $http_host, which is the raw header value and can be empty. The distinction rarely matters in practice, but using $host is the documented default choice and it behaves correctly when a client connects by IP address. The X-Forwarded-For value, $proxy_add_x_forwarded_for, takes any existing forwarded list and appends the address that connected to Nginx, so a chain of proxies preserves the full path instead of overwriting it.
One inheritance rule catches almost everyone. proxy_set_header directives are inherited from the enclosing level only when the current level defines none of them. The moment you add a single proxy_set_header inside a location, that location stops inheriting all of the headers defined at the server or http level. The practical consequence is simple: if you set headers at the server level and then add one more header in a location, the location loses the server level headers unless you repeat them. Either define all headers in every location, or define them once at the server level and never add more inside a location. Mixing the two approaches is how applications end up receiving the Host header but not the real IP, or the scheme but not the forwarded chain.
Applications also need to be told to trust these headers. A framework that ignores X-Forwarded-Proto will keep generating HTTP links on an HTTPS site, causing redirect loops and mixed content warnings. Most frameworks have a setting for trusting proxy headers: enable it for the Nginx address only, because a forwarded header from an untrusted client is trivially forged, and verify the result by requesting the site over HTTPS.
HTTPS Termination with TLS Certificates
HTTPS termination is the point where Nginx takes over encryption. The browser connects to Nginx over TLS, Nginx decrypts the request, forwards it to the backend over plain HTTP on the local network, encrypts the response, and sends it back. The backend never sees a certificate, and the certificate only needs to exist in one place, on the proxy. This is the standard production arrangement, and it works because the hop between Nginx and the backend is on a trusted local network rather than the open internet.
Start with a certificate. The free and widely used option is Let’s Encrypt, issued through the Certbot tool, which can also write the Nginx configuration for you. If Certbot manages the certificate, it will add the certificate lines and a redirect from HTTP to HTTPS itself. The resulting server block looks like the example below, and understanding each line matters even when a tool wrote it.
server {
listen 443 ssl;
server_name app.example.com;
ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3000;
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;
}
}
server {
listen 80;
server_name app.example.com;
return 301 https://$host$request_uri;
}
The first server block listens on port 443 with TLS enabled and points at the certificate and private key files. The second block listens on port 80 and redirects every request to the HTTPS version of the same URL, using a permanent 301 redirect so browsers and search engines learn the HTTPS address. The $host variable preserves the domain the visitor requested, and $request_uri preserves the full original path and query string, so a bookmarked HTTP link lands on the right HTTPS page rather than the home page.
Certificates expire and must be renewed. Let’s Encrypt certificates last for a short period by design, and Certbot normally installs a renewal timer that checks twice a day and renews any certificate near expiry. Verify the timer exists with the systemd timer list, and test a dry run renewal before you need it in production. A certificate that expires silently takes the whole site down, and it is one of the most avoidable outages in this entire subject. Also protect the private key file. It should be readable only by the Nginx process and the administrator, and it should never be copied into a repository or a container image.
When the backend itself needs to know the request was HTTPS, the X-Forwarded-Proto header does that job, as covered in the previous section. Without it, an application that builds absolute URLs will generate HTTP links on an HTTPS site, and an application that forces HTTPS with a redirect will redirect the proxied request back to HTTPS in a loop, because from the application’s point of view every request arrives over HTTP. If you see a redirect loop after enabling TLS, the missing forwarded protocol header is the first thing to check, and the second is the application’s trusted proxy setting.
Proxying WebSockets
WebSockets start as an ordinary HTTP request that asks the server to switch protocols, and that upgrade request is where most proxy configurations fail. The official WebSocket proxying documentation explains the subtlety: the Upgrade and Connection headers are hop by hop headers, which means they are not passed from a client to a proxied server by default. Nginx must be told to forward them explicitly, and the proxied server must answer with a 101 Switching Protocols response before Nginx opens the tunnel between client and backend.
Since version 1.3.13, Nginx supports a special mode that sets up this tunnel once the backend returns a 101 response, and the configuration is a small addition to a normal location. The HTTP version matters too: the protocol switch mechanism is available in HTTP/1.1, and the documentation notes that setting proxy_http_version 1.1 was required before version 1.29.7, after which 1.1 became the default. Setting it explicitly is harmless on newer versions and required on older ones, so include it in any configuration that must work across versions.
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 443 ssl;
server_name app.example.com;
location /chat/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_read_timeout 86400;
}
}
}
The map block sits in the http context and translates the client’s Upgrade header into the right Connection value: upgrade when the client asked for a protocol switch, and close for ordinary requests. Without the map, a location that always sends Connection: upgrade will confuse plain HTTP requests to the same path. The map keeps one location working for both kinds of traffic, which is useful when the same path serves a web page and a socket endpoint.
Timeouts are the second WebSocket trap. By default, the connection is closed if the proxied server sends no data within 60 seconds, and that default comes from proxy_read_timeout, which also governs ordinary proxied requests. A chat user who reads for two minutes without typing would lose the connection under the default, so WebSocket locations typically raise the timeout substantially, as in the example above. The alternative is to have the server send periodic ping frames, which reset the timeout and confirm the connection is still alive. Either approach works, but you must choose one deliberately. Raising the timeout for the WebSocket location only, rather than globally, keeps slow ordinary requests from hanging for hours when a backend stalls.
Upstreams, Timeouts, Buffering and Troubleshooting
When one backend is not enough, Nginx can spread requests across several with an upstream group. The group names the backends, and proxy_pass points at the group name instead of a single address. By default Nginx distributes requests round robin, one to each backend in turn, and marks a backend unavailable after a failed connection attempt. This is the simplest form of load balancing, and it is enough for the common case of two or three identical application instances behind one proxy.
upstream app_backend {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://app_backend;
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;
}
}
Session persistence is the first question to ask before adding a second backend. If the application stores session data in memory on one instance, a user whose requests alternate between instances will be logged out repeatedly. The fix is to store sessions in a shared store such as a database or a cache, which is worth setting up before you add a second instance rather than after users report the problem. Our Kubernetes Ingress tutorial covers the same load balancing ideas at the cluster level, where an Ingress controller performs the same role for services inside Kubernetes.
Timeouts decide how long Nginx waits at each stage of a proxied request. proxy_connect_timeout is how long Nginx waits to establish a connection to the backend. proxy_send_timeout is how long it waits between two writes to the backend. proxy_read_timeout is how long it waits between two reads from the backend, and its default is 60 seconds. A request that legitimately takes longer than 60 seconds, such as a large report or a file upload, will fail unless the read timeout is raised for that location. Raise timeouts per location rather than globally, and only for the endpoints that need them, because a global increase turns a stalled backend into a pool of hung connections.
Buffering is another setting that surprises newcomers. By default Nginx buffers the backend response, reading it into memory or a temporary file and sending it to the client in efficient chunks, which frees the backend quickly. For streaming responses, such as server sent events or a live log tail, buffering must be disabled with proxy_buffering off, or the client will see nothing until the response completes.
Most proxy problems announce themselves in the error log with a clear cause. A 502 Bad Gateway means Nginx could not reach the backend at all, usually because it is not running or the address is wrong. A 504 Gateway Timeout means the backend accepted the connection but did not answer within the read timeout, which points at a slow backend or a timeout set too low. A redirect loop after enabling HTTPS points at the forwarded protocol header or the application’s trusted proxy setting. A WebSocket that connects and then drops after a minute points at the read timeout. In every case, read the error log first with a command such as tail -f /var/log/nginx/error.log, reproduce the problem once while watching it, and fix what the log actually says.
Frequently Asked Questions
What is the difference between a reverse proxy and a load balancer?
A reverse proxy forwards client requests to a backend and returns the response, and load balancing is one of the things it can do while forwarding. A load balancer is a reverse proxy configured to distribute requests across several backends. Nginx does both: a single backend configuration is a reverse proxy, and an upstream group turns the same configuration into a load balancer. The terms describe roles, not different products.
Why does my application see 127.0.0.1 as the visitor address?
Because Nginx connects to the backend from its own address, and the application logs the address that connected to it. Add the forwarded headers from this tutorial, specifically X-Real-IP and X-Forwarded-For, and configure the application or framework to read them. If the application still logs the proxy address after that, the framework’s trusted proxy setting is not enabled, or it trusts a different address than the one Nginx connects from.
Should the backend listen on localhost or on all interfaces?
Bind the backend to localhost unless another machine genuinely needs to reach it directly. A backend bound to all interfaces is reachable by anyone who can reach the machine, which defeats the purpose of putting a proxy in front of it. Binding to localhost means only processes on the same machine, which in practice means only Nginx, can connect. If the backend runs in a container, publish its port to localhost only rather than to all interfaces.
Why do WebSockets work locally but fail behind the proxy?
Almost always because the Upgrade and Connection headers are not being forwarded, or because the HTTP version is not 1.1. Check that the location sets both headers, that the map for the Connection value is present, and that proxy_http_version is set to 1.1. If the socket connects and then drops after about a minute, the cause is the read timeout instead: raise proxy_read_timeout for the socket location or have the server send periodic pings.
Can one Nginx server proxy several applications?
Yes, and it is one of the main reasons to use a reverse proxy. Give each application its own server block with its own server_name, or its own location under a shared domain, and point each one at a different backend port or upstream group. Each application keeps its own headers, timeouts, and TLS certificate, and a problem in one backend does not affect the others except through the shared Nginx process itself.
Conclusion
A Nginx reverse proxy is a small configuration with a large effect on how an application behaves in production. The proxy_pass directive does the forwarding, the trailing slash rule decides what path the backend receives, the forwarded headers restore the information the application needs, TLS termination keeps encryption in one place, and the WebSocket headers open the tunnel that live features depend on. Each piece is simple on its own, and the mistakes come from the interactions: a header set in the wrong place, a slash that changes a path, or a timeout that closes a connection nobody expected to be timed.
Build the configuration in the order this tutorial presents it. Start with plain HTTP proxying and prove it works with curl. Add the headers and confirm the application sees the real visitor. Add TLS and confirm the redirect works. Add WebSockets last, and test with a real socket connection rather than a browser page load. Keep the configuration in source control, test it with nginx -t before every reload, and read the error log before guessing at a fix. A proxy configured this way is boring in the best sense: it works, it stays out of the way, and it lets the application do its job.



