CORS Header Gone After Using Nginx Proxy

Abstract: Resolve missing CORS headers in Nginx by configuring explicit Access-Control-Allow-Origin and handling OPTIONS preflight requests with the always directive.

Created: 2026-08-20 by
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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More