How to Resolve CORS Issues with Nginx: A Hands‑On Demo
This guide explains the same‑origin policy, demonstrates a cross‑origin request failure between two servers, and provides step‑by‑step Nginx configuration and JavaScript code to enable CORS headers so the request succeeds.
The same‑origin policy is a fundamental browser security rule that requires the protocol, domain (or IP), and port of a request to match the origin page; otherwise a cross‑origin request is blocked.
When two servers, A and B, do not satisfy this policy, an AJAX request from a page on server A to server B triggers a CORS error.
Demo Setup
1. Create a.html in Nginx’s html directory:
<html>
<head>
<meta charset="utf-8">
<title>跨域问题演示</title>
<script src="jquery.js"></script>
<script>
$(function(){
$("#btn").click(function(){
$.get('http://192.168.200.133:8080/getUser', function(data){
alert(JSON.stringify(data));
});
});
});
</script>
</head>
<body>
<input type="button" value="获取数据" id="btn" />
</body>
</html>2. Configure Nginx on server B ( nginx.conf) to return JSON data:
# B server
server {
listen 8080;
server_name localhost;
location /getUser {
default_type application/json;
return 200 '{"id":1,"name":"TOM","age":18}';
}
}
# A server
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html;
}
}3. Access a.html in a browser; the request to http://192.168.200.133:8080/getUser fails due to CORS.
Solution – Adding CORS Headers
Use the add_header directive in Nginx to send the required response headers:
location /getUser {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE; // adjust as needed
default_type application/json;
return 200 '{"id":1,"name":"TOM","age":18}';
}The Access-Control-Allow-Origin header specifies which origins may access the resource ("*" allows all), and Access-Control-Allow-Methods lists the permitted HTTP methods.
After reloading Nginx, the AJAX request succeeds and the JSON data is displayed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
