SoFunction
Updated on 2025-03-10

Example of code for nginx to forward front-end requests to back-end as a proxy

As a reverse proxy server, Nginx can handle proxy forwarding requests well. It can forward client requests to the backend server and return the backend server response to the client (avoiding sending requests directly to the backend and hiding the backend server address). The following describes how to configure Nginx for proxy forwarding and basic configuration.

Use docker to build nginx image configuration file to give an example, add /api to the corresponding configuration file code block

http

server {
        listen 80;  # Listen to the port
        server_name ;  # Server domain name or IP
        location /api {
            proxy_pass http://backend-server:8080;  # Proxy forwarding address            proxy_set_header Host $host;  # Forward the header, retain the original host name            proxy_set_header X-Real-IP $remote_addr;  # Forward the real IP of the client            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  # Forward the original IP address            proxy_set_header X-Forwarded-Proto $scheme;  # Forwarding Protocol (HTTP/HTTPS)        }

        location / {
            # Process other requests (such as static files, etc.)            root /var/www/html;  # Specify the root folder            index  ;
        }
    }

https 

server {
    listen 443 ssl;  # Listen to HTTPS    server_name ;

    ssl_certificate /etc/ssl/certs/;  # SSL certificate path    ssl_certificate_key /etc/ssl/private/;  # SSL private key path
    location /api {
        proxy_pass http://backend;  # Proxy forwarding address        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;
    }
}
  • proxy_pass: Specifies the destination address for the request forwarding, which can be a URL or an upstream host group.
  • proxy_set_header: Set forwarding headers, which are usually used to pass information such as the client's real IP and protocol.
  • upstream: Define an upstream server group to use in load balancing.

To better monitor and debug the process, access and error logs can be added in the Nginx configuration:

http {
    access_log /var/log/nginx/;  # Access log path    error_log /var/log/nginx/;    # Error log path}

Summarize

This is the article about nginx as a proxy forwarding front-end requests to the back-end. For more related content related to nginx forwarding front-end requests to the back-end, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!