SoFunction
Updated on 2025-05-06

Full parsing of Nginx forward proxy and reverse proxy and configuration files

1. Introduction and application scenarios of Nginx

Nginx is a high-performance open source web server and reverse proxy server, which is widely used in high concurrency scenarios, such as static resource hosting, load balancing, API gateways, etc. Its core advantages include:

  • Event-driven model: Asynchronous non-blocking architecture, supports tens of thousands of concurrent connections.
  • Modular design: Extended functions through modules (such as HTTP/2, gzip compression).
  • Lightweight and efficient: Low memory footprint, suitable for resource-constrained environments.

Typical application scenarios

  • Static file hosting
  • Reverse proxy dynamic applications (such as Java services)
  • Load balancing cluster
  • Security protection (such as DDoS defense, HTTPS encryption)

2. The core difference between forward proxy and reverse proxy

2.1 Forward Proxy

  • definition: Agent client accesses external resources,The client actively configures the proxy
  • Features
    • Hide the real IP of the client (such as the company's intranet access to the Internet).
    • Break through access restrictions (such as accessing blocked websites).

Configuration example

server {
    listen 3128;                      # Listen to the port    resolver 8.8.8.8;                 # DNS resolution server    location / {
        proxy_pass http://$http_host;  # Forward all requests    }
}

2.2 Reverse Proxy

  • definition: The proxy server receives client requests,Client-free backend service
  • Features
    • Hide backend servers to provide load balancing and security protection.
    • Supports dynamic application acceleration (such as cache, SSL termination).

Configuration example: 

server {
    listen 80;
    server_name ;
    location / {
        proxy_pass http://backend_server;  # Forward to the backend cluster        proxy_set_header Host $host;       # Pass the original domain name    }
}

Comparative summary

characteristic Forward proxy Reverse proxy
Configure the body Client Server side
Hide objects Client IP Backend service IP
Typical uses Access control, anonymous access Load balancing, safety protection

3. Overview of Nginx configuration file structure

The default path to Nginx configuration file is/etc/nginx/, supports modular design and includes the following core levels:

# Global Block (Main Context)user nginx;
worker_processes auto;
# events block (Events Context)events {
    worker_connections 1024;
}
# http block (HTTP Context)http {
    # HTTP global configuration    include ;
    # server block (virtual host)    server {
        # server block configuration        listen 80;
        # location block (request path matching)        location / {
            root /var/www/html;
        }
    }
}
# stream block (TCP/UDP proxy, optional)stream {
    server {
        listen 3306;
        proxy_pass backend_mysql;
    }
}

Full analysis of configuration file structure

1. Global Block (Main Context)

  • Range of action: Affects the global configuration of the entire Nginx process.
  • Core Instructions
user nginx;                     # Users and groups running Nginx (Safety Required)worker_processes auto;          # Number of worker processes (recommended to set as the number of CPU cores)error_log /var/log/nginx/ warn;  # Error log path and level (debug/info/Notice/warn/error)pid /var/run/;        # Store the main processPIDFile path

Block (Events Context)

  • Range of action: Define event model parameters for Nginx to handle network connections.
  • Core Instructions
events {
    worker_connections 1024;   # Maximum number of concurrent connections for a single worker process (total concurrency = worker_processes × worker_connections)    use epoll;                 # Event model (Linux recommends epoll, freeBSD uses kqueue)    multi_accept on;           # Accept all new connections at once    accept_mutex off;          # It is recommended to turn off the mutex lock (reduce context switching) when high concurrency is high}

Block (HTTP Context)

3.1 httpBlock global instructions

  • Range of action: Global configuration of all HTTP requests.
  • Core Instructions
http {
    # Basic configuration    include /etc/nginx/;      # Contains MIME type definition file    default_type application/octet-stream;  # Default response type (used when unknown file type)    # Log configuration    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" "$http_user_agent"';
    access_log /var/log/nginx/ main;  # Access log path and format    error_log /var/log/nginx/ warn;
    # Performance optimization    sendfile on;                # Enable efficient file transfer mode    tcp_nopush on;              # Only valid when sendfile is enabled to reduce the number of network packets    keepalive_timeout 65;       # Long connection timeout (units of seconds)    client_max_body_size 100m;  # Maximum limit on client request body (dDoS prevention)    # Compress configuration    gzip on;
    gzip_types text/plain text/css application/json;
    # Security enhancement    server_tokens off;          # Hide Nginx version number}

3.2 server block (virtual host configuration)

  • Range of action: Define a single virtual host (onehttpBlocks can contain multipleserverpiece).
  • Core Instructions
server {
    listen 80;                  # Listen port (you can specify IP, such as listen 192.168.1.1:80)    server_name ;    # Match domain names (supports wildcards and regular expressions)    root /var/www/html;         # Website root directory    index ;           # Default homepage file    # SSL configuration (HTTPS)    listen 443 ssl;
    ssl_certificate /etc/ssl/certs/;
    ssl_certificate_key /etc/ssl/private/;
    # Access control    deny 192.168.1.100;         # Disable access to specific IPs    allow all;
    # Error page redirection    error_page 404 /;
    error_page 500 502 503 504 /;
}

3.3 locationBlock (request path matching)

  • Range of action:existserverDefinition within the block, according to the URI path matching processing rules.
  • Matching mode
    • Exact matchlocation = /path { ... }
    • Prefix matchinglocation /prefix/ { ... }
    • Regular Match
      • location ~ \.php$ { ... }(case sensitive)
      • location ~* \.jpg$ { ... }(Case insensitive)

Common instructions

  • location / {
        try_files $uri $uri/ /;  # Static files are preferred to match, if they do not exist, they will return to the homepage}
    location /images/ {
        alias /data/static/images/;       # Path alias (replace /images/ in URI)    expires 30d;                      # Browser cache for 30 days}
    location /api/ {
        proxy_pass http://backend_server;  # Reverse proxy to backend service    proxy_set_header Host $host;       # Pass the original domain name    proxy_set_header X-Real-IP $remote_addr;  # Pass the real IP of the client}
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;      # Forward PHP request to FastCGI service    include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

3.4 upstreamBlock (load balancing configuration)

  • Range of action:existhttpDefine a backend server cluster within the block for load balancing.
  • Core Instructions
upstream backend {
    # Load balancing policy (default polling)    least_conn;                # Minimum number of connections policy    # ip_hash; # Assign by client IP hash (session keeping)    # Backend server list    server 10.0.0.1:8080 weight=3;  # The higher the weight, the more allocation requests    server 10.0.0.2:8080;
    server 10.0.0.3:8080 backup;    # Backup server (enabled when the primary server is down)}
server {
    location / {
        proxy_pass http://backend;  # Clusters configured using upstream    }
}

3.5streamBlock (TCP/UDP proxy)

  • Range of action: Handle non-HTTP traffic (such as database, SSH, DNS).
  • Core Instructions
stream {
    upstream backend_mysql {
        server 10.0.0.1:3306;
        server 10.0.0.2:3306;
    }
    server {
        listen 3306;          # Listen to TCP ports        proxy_pass backend_mysql;
        proxy_connect_timeout 5s;
    }
}

5. Configuration file examples and comments

# Global Blockuser www-data;
worker_processes auto;
error_log /var/log/nginx/ warn;
# events blockevents {
    worker_connections 2048;
    use epoll;
}
# http blockhttp {
    include ;
    default_type application/octet-stream;
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" "$http_user_agent"';
    access_log /var/log/nginx/ main;
    sendfile on;
    keepalive_timeout 65;
    # Virtual Host 1: Static Resource Service    server {
        listen 80;
        server_name ;
        root /var/www/static;
        location / {
            expires 7d;
            add_header Cache-Control "public";
        }
    }
    # Virtual Host 2: Reverse Proxy Dynamic Application    server {
        listen 80;
        server_name ;
        location / {
            proxy_pass http://backend;
            proxy_set_header Host $host;
        }
    }
    # Load balancing configuration    upstream backend {
        server 10.0.0.1:8080;
        server 10.0.0.2:8080;
    }
}
# stream block (MySQL load balancing)stream {
    upstream mysql_cluster {
        server 10.0.0.1:3306;
        server 10.0.0.2:3306;
    }
    server {
        listen 3306;
        proxy_pass mysql_cluster;
    }
}

This is the article about the full parsing of Nginx forward proxy and reverse proxy and configuration files. For more related contents of nginx forward proxy and reverse proxy, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!