Learn Nginx · 5/13

Reverse Proxy Fundamentals

5 min read

What is a Reverse Proxy and Why Use It? 🤔

A reverse proxy is a server that sits between clients and backend servers. It receives client requests, forwards them to the appropriate backend server, and then returns the server's response to the client. This setup enhances security by masking the real IP address and architecture of your server, blocking malicious traffic, and centralizing SSL management, rate limiting, and authentication.

Key Benefits:

  • Load Balancing: Distributes incoming traffic across multiple backend servers to prevent any single server from becoming a bottleneck.
  • Enhanced Security: Hides the IP addresses of backend servers and can provide a single point for security monitoring and SSL/TLS termination.
  • Improved Performance: Caches content to reduce the load on backend servers and compresses data to minimize bandwidth usage.
  • Simplified Management: Provides a centralized point for logging, authentication, and managing traffic to various backend services.

Nginx is a popular choice for a reverse proxy due to its high performance, scalability, and event-driven architecture that can handle thousands of concurrent connections with minimal resource usage. Industry giants like Netflix, GitHub, and Airbnb use Nginx for content delivery, reverse proxying, and load balancing.

Basic Proxying: Configuring the proxy_pass Directive ⚙️

The cornerstone of Nginx's reverse proxy functionality is the proxy_pass directive. This directive is used within a location block to specify the URL of the backend server to which requests should be forwarded.

Minimal Configuration

Here is a basic example of how to configure Nginx to act as a reverse proxy:

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

In this configuration, all requests to example.com are forwarded to a backend server running on localhost at port 3000.

proxy_pass with and without a URI

The behavior of proxy_pass changes depending on whether a URI is included in the directive.

  • Without a URI: If no URI is specified at the end of the server address in the proxy_pass definition, the original request URI is passed to the upstream server as is. For example, if a request for /some/path/page.html is received, it will be forwarded to http://backend-server/some/path/page.html.

    nginx
    location /some/path/ {
        proxy_pass http://backend-server;
    }
  • With a URI: If a URI is specified in the proxy_pass directive, it replaces the part of the request URI that matches the location parameter. For example, a request for /some/path/page.html will be proxied to http://backend-server/new-path/page.html.

    nginx
    location /some/path/ {
        proxy_pass http://backend-server/new-path/;
    }

Preserving Client Identity: Passing Essential Headers (Real-IP, Host) 🕵️

When Nginx acts as a reverse proxy, the backend server sees the request as coming from Nginx's IP address. To provide the backend server with information about the original client, it's crucial to pass along certain headers.

  • Host: By default, Nginx sets the "Host" header of the proxied request to the value of the $proxy_host variable. It is often desirable to pass the original Host header from the client's request.
  • X-Real-IP: This header is used to convey the original IP address of the client.
  • X-Forwarded-For: This is a standard header for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or a load balancer.

Configuration Example

Here’s how you can set these headers in your Nginx configuration:

nginx
location / {
    proxy_pass http://backend-server;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

This configuration ensures that the backend server receives the original host and the client's IP address.

Connection Management: Proxy Buffers and Timeouts ⏱️

Properly managing connections between Nginx and the backend servers is vital for performance and reliability.

Proxy Buffers

Nginx uses buffers to temporarily store the response from the backend server before sending it to the client. This allows Nginx to quickly receive the response from the backend, freeing up the backend to handle other requests, and then deliver the response to the client at a pace the client can handle.

Buffering is enabled by default in Nginx. Key directives for managing buffers include:

  • proxy_buffering on | off;: Enables or disables buffering.
  • proxy_buffer_size size;: Sets the size of the buffer used for reading the first part of the response from the proxied server, which usually contains the response header.
  • proxy_buffers number size;: Sets the number and size of buffers used for a single connection.

Here's an example of customized buffer settings:

nginx
location / {
    proxy_pass http://backend-server;
    proxy_buffering on;
    proxy_buffer_size 1k;
    proxy_buffers 24 4k;
    proxy_busy_buffers_size 8k;
}

Proxy Timeouts

Timeouts prevent Nginx from waiting indefinitely for a slow backend server, which could exhaust resources and make the application unresponsive. The primary timeout directives are:

  • proxy_connect_timeout: The maximum time for establishing a connection with the proxied server. The default is 60 seconds.
  • proxy_send_timeout: The timeout for sending a request to the proxied server. This timeout is between two successive write operations, not for the entire request. The default is 60 seconds.
  • proxy_read_timeout: The timeout for reading a response from the proxied server. This timeout is between two successive read operations, not for the entire response. The default is 60 seconds. This is a common directive to adjust to prevent 504 Gateway Timeout errors for long-running processes.

An example of setting custom timeouts:

nginx
location / {
    proxy_pass http://backend-server;
    proxy_connect_timeout 90s;
    proxy_send_timeout 90s;
    proxy_read_timeout 90s;
}

Further Reading and References 📚

Challenge

You are tasked with configuring an Nginx reverse proxy for api.example.com. Your configuration must handle requests for general API access, large file uploads, and an internal admin panel, each with specific requirements.

Write the complete server block to meet the following criteria:

  1. The server must listen on port 80 for the server name api.example.com.
  2. Configure a default location (/) to forward all requests to a backend service located at http://10.0.0.5:8080.
  3. Within this default location, ensure the backend receives the original Host header and the client's real IP address using the X-Real-IP header.
  4. Create a second location block specifically for /uploads/. Requests to this path should be proxied to a dedicated upload service at http://10.0.0.6:9000/.
  5. For the /uploads/ location, proxy buffering must be disabled to handle large, streaming uploads efficiently.
  6. The read timeout for the upload service proxy must be set to 300 seconds to accommodate slow uploads.
  7. Create a third location block for /admin/. These requests must be forwarded to an internal admin service at http://192.168.1.10:5000/. The request URI passed to the backend should not include the /admin/ prefix.
  8. Globally for this server block, set the timeout for establishing a connection with any backend server to 10 seconds.

Expected result

Your Nginx configuration should define a single server block within the http context. This server block should listen on port 80 for api.example.com and contain three distinct location blocks to correctly route traffic based on the request URI.

The final configuration should look similar to this:

nginx
http {
    server {
        listen 80;
        server_name api.example.com;

        proxy_connect_timeout 10s;

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

        location /uploads/ {
            proxy_pass http://10.0.0.6:9000/;
            proxy_buffering off;
            proxy_read_timeout 300s;
        }

        location /admin/ {
            proxy_pass http://192.168.1.10:5000/;
        }
    }
}

Key Points in the Correct Solution:

  • listen 80; and server_name api.example.com; correctly configure the server to handle the specified traffic.
  • proxy_connect_timeout 10s; is set at the server level, applying to all proxy connections within it.
  • The location / block uses proxy_pass without a trailing URI to forward requests as-is. proxy_set_header directives correctly pass client information.
  • The location /uploads/ block uses proxy_buffering off; to disable buffering and proxy_read_timeout 300s; to increase the timeout for long-running requests.
  • The location /admin/ block uses proxy_pass http://192.168.1.10:5000/; with a trailing slash. This trailing slash on the URL tells Nginx to replace the part of the URI matching the location (/admin/) with the URI specified in proxy_pass (in this case, just /), effectively stripping the prefix.
nginx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.