0
0
NginxHow-ToBeginner · 4 min read

How to Use proxy_pass in Nginx: Syntax and Examples

Use the proxy_pass directive inside an Nginx location block to forward client requests to another server or service. It acts as a reverse proxy, sending requests to the specified URL or IP address and returning the response to the client.
📐

Syntax

The proxy_pass directive is used inside a location block to specify the backend server URL where requests should be forwarded. It supports HTTP, HTTPS, and UNIX socket addresses.

Key parts:

  • location: Defines the URL path to match.
  • proxy_pass: The backend server URL or IP to forward requests.
nginx
location /path/ {
    proxy_pass http://backend_server:8080/;
}
💻

Example

This example shows how to forward all requests from /app/ on the Nginx server to a backend server running on http://localhost:3000. Nginx acts as a reverse proxy.

nginx
server {
    listen 80;
    server_name example.com;

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

Common Pitfalls

Common mistakes when using proxy_pass include:

  • Missing trailing slash in proxy_pass URL causing incorrect URI forwarding.
  • Not setting necessary headers like Host or X-Real-IP, which can break backend logic.
  • Incorrect location matching leading to unexpected request routing.

Example of wrong vs right usage:

nginx
location /app/ {
    # Wrong: missing trailing slash causes URI to append incorrectly
    proxy_pass http://localhost:3000;
}

location /app/ {
    # Right: trailing slash ensures correct URI forwarding
    proxy_pass http://localhost:3000/;
}
📊

Quick Reference

DirectivePurposeExample
proxy_passForward requests to backend serverproxy_pass http://backend:8080/;
proxy_set_headerSet headers sent to backendproxy_set_header Host $host;
locationMatch request URI pathlocation /api/ { ... }
listenDefine server portlisten 80;
server_nameDefine server hostnameserver_name example.com;

Key Takeaways

Use proxy_pass inside a location block to forward requests to a backend server.
Always include a trailing slash in proxy_pass URL to correctly forward URIs.
Set proxy_set_header directives to pass client info to the backend.
Test your configuration to avoid common URI forwarding mistakes.
proxy_pass enables Nginx to act as a reverse proxy for load balancing or security.