SoFunction
Updated on 2025-03-05

Complete Guide to Solving Cross-Domain Issues and Passing Request Headers Using Nginx Proxy

introduction

Cross-domain resource sharing (CORS) is a common problem in modern web development. When your front-end application tries to request resources from one domain name, the browser blocks such requests unless the target server explicitly allows cross-domain access. To solve this problem, developers usually use a proxy server to forward requests, thereby bypassing the browser's homologous policy.

This article will explain in detail how to use Nginx as a proxy server to solve cross-domain problems and ensure that front-end request headers (such as cookies, User-Agent, Accept, etc.) can be correctly passed to the target server. We will start with the basic configuration of Nginx and gradually deepen, and finally form a complete solution.

1. What is a cross-domain problem?

Cross-domain issues are caused by the browser's homologous policy. The same-origin policy requires that the browser can only allow requests from the same domain name, but block requests from other domain names. Specifically, if the domain name of the front-end application is http://localhost:8080 and the domain name of the target API is :31432, then the browser will block such cross-domain requests.

1.1 Performance of cross-domain problems

When you try to initiate a cross-domain request from the front end, the browser returns an error like the following:

Access to XMLHttpRequest at ':31432/interface/orderPhone?txm=320328706913678&type=1' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1.2 Common ways to solve cross-domain problems

  • CORS header configuration: Configure on the target serverAccess-Control-Allow-OriginHeader, allows cross-domain requests for specific domain names.
  • JSONP: Created through dynamic<script>Tags bypass cross-domain restrictions, but only support GET requests.
  • Proxy server: Use a proxy server to forward requests, thereby bypassing the browser's homologous policy.

This article will focus on how to use Nginx as a proxy server to solve cross-domain problems.

2. Use Nginx as proxy server

Nginx is a high-performance HTTP server and reverse proxy server. By configuring Nginx, we can forward the front-end requests to the target server and add the necessary CORS headers to the response to solve the cross-domain problem.

2.1 Basic configuration of Nginx

Here is a simple example of Nginx configuration file:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       ;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index   ;
        }

        error_page   500 502 503 504  /;
        location = / {
            root   html;
        }
    }
}

In this configuration, Nginx listens80port and forward the request to the localhtmlTable of contents.

2.2 Add cross-domain support

To support cross-domain requests, we need to add the following to the Nginx configuration:

server {
    listen       80;
    server_name  localhost;

    # Support cross-domain configuration    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

    location / {
        root   html;
        index   ;
    }

    error_page   500 502 503 504  /;
    location = / {
        root   html;
    }
}

In this configuration, we addedadd_headerDirective to set the CORS header to allow cross-domain requests for all domain names.

3. Configure the Nginx proxy to pass request headers

By default, Nginx forwards request headers (such as Accept, Cookies, User-Agent, etc.) sent by the client (browser) to the target server. However, if you explicitly set certain request headers (such as Host, X-Real-IP, etc.) in your Nginx configuration, the original request headers may be overwritten or deleted.

To ensure that all request headers are correctly delivered to the target server, we need to adjust the Nginx configuration.

3.1 Modified Nginx configuration

Here is the modified Nginx configuration to ensure that all request headers are passed correctly:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       ;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        # Support cross-domain configuration        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

        location / {
            root   html;
            index   ;
        }

        # Proxy API Request        location /api/ {
            proxy_pass :31432/;  # Replace with your API server address
            # Keep the original request header            proxy_pass_request_headers on;

            # Set the necessary proxy header            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;

            # If you need to pass the original cookie, make sure that the cookie header is not overwritten            proxy_set_header Cookie $http_cookie;

            # If you need to pass the original User-Agent, make sure that the User-Agent header is not overwritten            proxy_set_header User-Agent $http_user_agent;

            # If you need to pass the original Accept, make sure that the Accept header is not overwritten            proxy_set_header Accept $http_accept;
        }

        error_page   500 502 503 504  /;
        location = / {
            root   html;
        }
    }
}

3.2 Key changes description

  1. proxy_pass_request_headers on;

    • This is the default behavior, ensuring that all client request headers are passed to the target server.
    • If you do not explicitly overwrite certain request headers, this step can be omitted.
  2. proxy_set_header

    • useproxy_set_headerSet the necessary proxy header (such asHostX-Real-IPwait).
    • For the original request header that needs to be retained (such asCookieUser-AgentAccept),use$http_<header_name>Variable passes original value.
  3. $http_<header_name>

    • $http_cookie: Pass the originalCookiehead.
    • $http_user_agent: Pass the originalUser-Agenthead.
    • $http_accept: Pass the originalAccepthead.

4. Verify that the request header is passed correctly

To ensure that the request header is correctly passed to the target server, you can verify it by:

  1. Check the log of the target server

    • Check the log on the target server to confirm whether the received request header is consistent with the one sent by the front end.
  2. Using debugging tools

    • Enable debug logs in Nginx to see if the request header is forwarded correctly:
error_log /var/log/nginx/ debug;

Log request headers in Nginx

  • Add logging in Nginx configuration and output request headers:
location /api/ {
    proxy_pass :31432/;
    access_log /var/log/nginx/;
    error_log /var/log/nginx/;

    # Record request header    add_header X-Debug-Request-Headers "$http_user_agent $http_cookie";
}

5. Adjustment of front-end code

If you use Nginx proxy, the front-end code isurlIt needs to be changed to a proxy address. For example:

// Target URL (changed to Nginx proxy address)const url = "http://your-nginx-server/api/interface/orderPhone?txm=320328706913678&amp;type=1";

// Request headerconst headers = {
  "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
  "Accept-Language": "zh-CN,zh;q=0.9",
  "Cache-Control": "max-age=0",
  "Connection": "keep-alive",
  "Cookie": "CASTGC=TGT-37528572-jMiSLXk2PqxLEdKk2lxzXfSwgfo5MYa3MdD; SESSION=OTdiOTQ4NDQtY2M2ZC00NmVjLTgwZmItNzMzNDVjZDlmNmU4",
  "DNT": "1",
  "Upgrade-Insecure-Requests": "1",
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
};

// Make a requestfetch(url, {
  method: "GET", // Request method  headers: headers, // Request header  credentials: "include" // Include cookies})
  .then(response =&gt; {
    if (!) {
      throw new Error(`HTTP error! status: ${}`);
    }
    return (); // parse the response to text  })
  .then(data =&gt; {
    ("Response data:", data); // Output response data  })
  .catch(error =&gt; {
    ("Error:", error); //Catch error  });

6. Summary

Through this article, we explain in detail how to use Nginx as a proxy server to solve cross-domain problems and ensure that the front-end request header can be correctly passed to the target server. The following is a summary of key points:

  1. The nature of cross-domain problems: The browser's homologous policy prevents cross-domain requests.
  2. The role of Nginx proxy: Forward requests through proxy servers, bypassing the browser's same-origin policy.
  3. Key points of Nginx configuration
    • useadd_headerSet the CORS header.
    • useproxy_set_headerPass the original request header.
  4. Verify request header: Make sure the request headers are passed correctly through logging and debugging tools.
  5. Front-end code adjustment: Change the destination URL to the proxy address.

This is the article about using Nginx proxy to solve cross-domain problems and pass request headers. For more related Nginx to solve cross-domain problems and pass request headers, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!