CORS headers disappear behind Nginx because the proxy intercepts the preflight OPTIONS request and fails to forward the necessary access-control-allow-origin, allow-methods, or allow-headers responses. The solution requires configuring Nginx to handle these OPTIONS requests explicitly, either by echoing them directly from the proxy or by ensuring the upstream application correctly processes and returns the headers for both simple and complex cross-origin requests.
Understanding the Preflight Mechanism
When a browser makes a cross-origin request that is not "simple" (such as those with custom headers, non-standard methods like PUT or DELETE, or specific content types), it first sends an HTTP OPTIONS request known as a preflight check. This request asks the server if the actual request is safe to send. If Nginx acts as a reverse proxy without specific configuration for this OPTIONS method, it may simply pass the request to the backend or return a generic 405 Method Not Allowed error. In many cases, the backend application (like a Go-Gin server) might ignore the OPTIONS request or return it without the required CORS headers, causing the browser to block the subsequent actual request.
The core issue is often that developers configure CORS headers only for GET, POST, or PUT methods in their application code, assuming Nginx will handle the rest. However, when Nginx sits in front, it becomes the first point of contact. If it does not recognize the OPTIONS request as a valid CORS preflight, it may strip headers or fail to respond with the correct status codes, leading to the "missing header" error observed in developer tools.
Configuring Static CORS Headers
For most use cases, the most robust approach is to handle CORS entirely within Nginx. This ensures consistent behavior regardless of the backend technology and reduces load on the application server. You must add specific headers to your
server or
location block. These headers tell the browser which origins are permitted, which HTTP methods are allowed, and whether credentials can be included.
Add the following directives to your Nginx configuration file:
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Authorization, Content-Type, Accept, Origin, User-Agent, DNT, Cache-Control, X-Mx-ReqToken, Keep-Alive, User-Token, X-Requested-With' always;
The
always parameter is critical. Without it, Nginx only adds these headers to successful responses (2xx and 3xx). If the backend returns an error (4xx or 5xx), the browser will still block the response because the CORS headers are missing. By using
always, you ensure the headers are present even on error pages, allowing the frontend to read the error details.
If your application supports multiple dynamic origins, you cannot hardcode
$http_origin due to security risks involving wildcard origins. Instead, you should validate the incoming origin against a whitelist. However, for internal services or single-client setups, using
$http_origin directly is standard practice. Note that you cannot use
Access-Control-Allow-Origin: * when credentials (cookies or authorization headers) are involved. In such cases, you must reflect the specific requesting origin.
Handling the OPTIONS Preflight Request
Even with headers defined, Nginx must actively respond to OPTIONS requests. By default, Nginx might try to serve a static file or pass the request to the backend, which may not be configured to answer. To fix this, you need a dedicated location block that catches OPTIONS requests and returns a 200 OK status immediately, along with the CORS headers.
Include this block in your server configuration:
location / {
# Handle preflight requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, Accept, Origin, User-Agent, DNT, Cache-Control, X-Mx-ReqToken, Keep-Alive, User-Token, X-Requested-With';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
# Proxy to backend
proxy_pass http://backend_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
This snippet uses an
if block inside the location context to detect OPTIONS methods. It sets the same headers as above, adds
Access-Control-Max-Age to cache the preflight result for 20 days (reducing repeated checks), and returns a 204 No Content status. This tells the browser that the preflight passed and it can proceed with the actual request. The
proxy_pass directive below handles all other methods, forwarding them to your Go-Gin or other backend service.
Verifying the Configuration
After updating your Nginx configuration, always test the syntax before reloading. Run
nginx -t to check for errors. If the test passes, reload the service with
systemctl reload nginx. To verify the fix, open your browser's developer tools, go to the Network tab, and trigger the request that previously failed. Look for the OPTIONS request in the list. It should now show a 204 status and include the
Access-Control-Allow-Origin header in the response. If the actual GET or POST request follows, ensure it also includes the CORS headers.
For related issues regarding SSL/TLS configurations that might interfere with header processing, see our guide on
Client Fails TLS Handshake: Troubleshooting Guide. Additionally, understanding how Nginx rewrites interact with API bodies can prevent further header loss, as detailed in
Troubleshooting Nginx Rewrite Overlapping with Swagger Body.
Common Pitfalls
One common mistake is placing the CORS headers in a separate
location block that does not cover the API endpoints. Ensure the
add_header directives are in the same scope as the
proxy_pass or in a parent
server block. Another pitfall is forgetting to clear browser caches. Browsers aggressively cache CORS preflight results. If you change your Nginx config but still see errors, try clearing the cache or testing in an incognito window.
Finally, ensure that your backend application does not override Nginx headers. If your Go-Gin app sets its own
Access-Control-Allow-Origin header, it might conflict with Nginx's reflection logic. It is best practice to let Nginx handle CORS completely when acting as a reverse proxy, leaving the backend to focus solely on business logic.
Frequently Asked Questions
Why do I get a 405 Method Not Allowed error?
This occurs because Nginx does not know how to handle the OPTIONS method for your specific location. Adding the explicit
if ($request_method = 'OPTIONS') block resolves this by returning a 204 status instead of passing the request to a backend that doesn't support OPTIONS.
Can I use wildcards for Access-Control-Allow-Origin?
You can use
* for simple requests, but it is insecure and forbidden when sending credentials like cookies or authorization tokens. Always reflect the specific
$http_origin when credentials are required to comply with browser security policies.
What is the difference between 200 and 204 in CORS responses?
A 204 No Content response is preferred for preflight requests because it indicates success without a body, saving bandwidth. A 200 OK is also acceptable but less efficient. Both work as long as the correct CORS headers are present in the response.
How do I debug missing headers in Chrome DevTools?
Check the Response Headers tab for the OPTIONS request. If the headers are absent, your Nginx config likely lacks the
always flag or the OPTIONS handling block. Also, verify that the "Network" panel is not filtering out certain request types during your inspection.
Does Nginx cache CORS preflight responses?
Nginx itself does not cache CORS headers, but the browser does based on the
Access-Control-Max-Age header value. Setting this to a high value like 1728000 seconds reduces the number of preflight requests the browser makes, improving performance for subsequent API calls.