How to Fix Cross‑Origin Issues with Nginx: A Step‑by‑Step Guide

This article explains the browser same‑origin policy, demonstrates a CORS problem using two servers with an AJAX request, and provides a complete Nginx configuration—including add_header directives—to enable cross‑origin access and resolve the error.

Liangxu Linux
Liangxu Linux
Liangxu Linux
How to Fix Cross‑Origin Issues with Nginx: A Step‑by‑Step Guide

Same‑Origin Policy Overview

The browser enforces a same‑origin policy: two URLs are considered same‑origin only when their protocol, host (or IP), and port are identical. If any of these differ, the request is treated as cross‑origin and may be blocked.

When Does a Cross‑Origin Issue Appear?

Consider two servers, A and B. A web page served by A sends an asynchronous request to B. Because A and B differ in protocol, IP, port, or domain suffix, the request violates the same‑origin policy and 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. Nginx configuration

B server (port 8080) returns 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 (port 80) serves the static HTML page

# A server
server {
  listen 80;
  server_name localhost;

  location / {
    root html;
    index index.html;
  }
}

When the page is opened in a browser and the button is clicked, the request to http://192.168.200.133:8080/getUser is blocked by the browser because the origins differ.

Solution: Add CORS Headers in Nginx

Use the add_header directive to send the required response headers from the B server:

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 are allowed ("*" permits all), and Access-Control-Allow-Methods lists the HTTP methods that can be used.

Result

After reloading Nginx with the updated configuration, the AJAX request succeeds and the browser displays the JSON data without CORS errors.

Reference: https://www.cnblogs.com/rtnb/p/15860442.html
CORS demo diagram
CORS demo diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Web DevelopmentCORSCross-OriginSame-Origin Policyajax
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

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.