0
0
NginxHow-ToBeginner · 4 min read

How to Configure Reverse Proxy in Nginx: Simple Guide

To configure a reverse proxy in nginx, use the location block with the proxy_pass directive pointing to the backend server URL. This setup forwards client requests to another server while keeping the original URL visible.
📐

Syntax

The basic syntax for configuring a reverse proxy in nginx involves the location block inside a server block. Use proxy_pass to specify the backend server address where requests should be forwarded.

  • server {}: Defines the virtual server.
  • location /path/ {}: Matches client request paths.
  • proxy_pass http://backend/;: Forwards requests to the backend server.
nginx
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:8080/;
    }
}
💻

Example

This example shows a simple reverse proxy setup where Nginx listens on port 80 and forwards all requests to a backend server running on localhost port 8080. The client sees example.com but the content is served by the backend.

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:8080/;
        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;
    }
}
Output
When a user visits http://example.com, Nginx forwards the request to http://localhost:8080 and returns the backend response transparently.
⚠️

Common Pitfalls

Common mistakes when configuring reverse proxy in Nginx include:

  • Forgetting the trailing slash in proxy_pass which can cause incorrect URL forwarding.
  • Not setting necessary headers like Host and X-Real-IP, which can break backend logic.
  • Not allowing the backend server to accept connections from Nginx.

Example of wrong vs right proxy_pass usage:

nginx
location /api/ {
    # Wrong: missing trailing slash causes path issues
    proxy_pass http://backend/api;
}

location /api/ {
    # Right: trailing slash ensures correct path forwarding
    proxy_pass http://backend/api/;
}
📊

Quick Reference

DirectivePurpose
proxy_passDefines the backend server URL to forward requests
proxy_set_header Host $host;Preserves original host header for backend
proxy_set_header X-Real-IP $remote_addr;Sends client IP to backend
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;Tracks original client IP chain
proxy_set_header X-Forwarded-Proto $scheme;Indicates HTTP or HTTPS protocol

Key Takeaways

Use the proxy_pass directive inside a location block to forward requests to the backend.
Always include trailing slashes in proxy_pass URLs to avoid path errors.
Set proxy headers like Host and X-Real-IP to preserve client information.
Test your configuration with nginx -t and reload nginx after changes.
Ensure backend servers accept connections from the Nginx proxy.