乐闻世界logo
搜索文章和话题

How to configure Nginx as a reverse proxy?

2月21日 16:57

How to configure Nginx as a reverse proxy?

Nginx reverse proxy refers to the Nginx server receiving client requests, then forwarding them to backend servers, and finally returning the backend server's response to the client. The client only knows about the Nginx server's existence and is unaware of the actual backend servers processing the requests.

Basic Configuration Example:

nginx
server { listen 80; server_name example.com; 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; proxy_set_header X-Forwarded-Proto $scheme; } } upstream backend_server { server 192.168.1.100:8080; server 192.168.1.101:8080; }

Key Configuration Directives Explained:

  1. proxy_pass: Specifies the backend server address, which can be an IP address, domain name, or upstream group name

  2. proxy_set_header: Sets request headers forwarded to the backend server

    • Host: Preserves the original request's hostname
    • X-Real-IP: Records the client's real IP
    • X-Forwarded-For: Records the proxy chain the request passed through
    • X-Forwarded-Proto: Records the original protocol (http/https)
  3. upstream: Defines a group of backend servers for load balancing

Common Reverse Proxy Configuration Options:

nginx
location /api/ { proxy_pass http://backend_api; # Timeout settings proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; # Buffer settings proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; # WebSocket support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; # Disable redirects proxy_redirect off; }

Load Balancing Strategies:

  1. Round-robin (default): Distributes requests in order
  2. least_conn: Assigns to the server with the fewest active connections
  3. ip_hash: Hashes based on client IP to ensure requests from the same IP go to the same server
  4. least_time: Assigns to the server with the shortest response time (requires commercial version)

Practical Use Cases:

  • Forwarding requests to multiple application servers
  • Hiding backend server real IPs
  • Unified entry point, simplifying client configuration
  • Implementing SSL termination
  • Caching static content
  • WebSocket proxying
标签:Nginx