Understanding and Solving Cross-Origin Issues with Nginx add_header Configuration
This article explains when cross‑origin problems occur due to the browser's same‑origin policy, describes the restrictions it imposes, and provides detailed Nginx add_header configurations—including specific and global examples—to enable Access‑Control‑Allow‑Origin and Access‑Control‑Allow‑Methods headers for CORS resolution.
The article addresses cross‑origin issues by first explaining the situations in which they arise and then presenting concrete solutions.
Cross‑origin occurs when a browser attempts to execute scripts from a different origin; this restriction is enforced by the same‑origin policy, a core security feature that checks protocol, domain, and port.
The same‑origin policy limits access to cookies, LocalStorage, IndexedDB, DOM objects, and prevents AJAX requests from non‑matching origins, typically resulting in errors such as "No 'Access-Control-Allow-Origin' header is present on the requested resource".
In a typical scenario, two servers A and B are involved; if a page on server A sends an asynchronous request to server B and the origins differ, the browser blocks the request, causing a cross‑origin problem.
The proposed solution is to use the add_header directive in Nginx to add the necessary HTTP headers that relax the same‑origin restrictions.
The syntax of the directive is:
add_header name value…
By adding the headers Access-Control-Allow-Origin (which can be set to a specific origin or "*") and Access-Control-Allow-Methods (e.g., GET, POST, PUT, DELETE), the server signals that cross‑origin requests are permitted.
Example configuration for a specific location:
// Set cross‑origin for a specific file
location /getUser {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;
default_type application/json;
return 200 '{"id":1,"name":"TOM","age":18}';
}
Example configuration for global cross‑origin support:
// Allow all hosts globally
location {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;
default_type application/json;
return 200 '{"id":1,"name":"TOM","age":18}';
}
Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
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.