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 server
Access-Control-Allow-Origin
Header, 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 listens80
port and forward the request to the localhtml
Table 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_header
Directive 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
-
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.
-
proxy_set_header
:- use
proxy_set_header
Set the necessary proxy header (such asHost
、X-Real-IP
wait). - For the original request header that needs to be retained (such as
Cookie
、User-Agent
、Accept
),use$http_<header_name>
Variable passes original value.
- use
-
$http_<header_name>
:-
$http_cookie
: Pass the originalCookie
head. -
$http_user_agent
: Pass the originalUser-Agent
head. -
$http_accept
: Pass the originalAccept
head.
-
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:
-
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.
-
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 isurl
It 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&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 => { if (!) { throw new Error(`HTTP error! status: ${}`); } return (); // parse the response to text }) .then(data => { ("Response data:", data); // Output response data }) .catch(error => { ("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:
- The nature of cross-domain problems: The browser's homologous policy prevents cross-domain requests.
- The role of Nginx proxy: Forward requests through proxy servers, bypassing the browser's same-origin policy.
-
Key points of Nginx configuration:
- use
add_header
Set the CORS header. - use
proxy_set_header
Pass the original request header.
- use
- Verify request header: Make sure the request headers are passed correctly through logging and debugging tools.
- 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!