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.

Open Source Linux
Open Source Linux
Open Source Linux
How to Resolve CORS Issues with Nginx: A Hands‑On Demo

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.

Cross‑origin demo illustration
Cross‑origin demo illustration
Browser test result
Browser test result
Web developmentCORSCross-Origin
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.