0
0
Nginxdevops~5 mins

CORS configuration in Nginx - Commands & Configuration

Choose your learning style9 modes available
Introduction
Web browsers block some requests from one website to another for security. CORS configuration tells the browser which websites are allowed to access resources on your server. This helps your web app work correctly when it talks to other servers.
When your frontend app on example.com needs to get data from api.example.org without errors
When you want to allow only specific websites to use your server's resources
When you want to prevent unknown websites from accessing your API
When you serve images or fonts that other websites can use safely
When you want to fix browser errors about blocked cross-site requests
Config File - nginx.conf
nginx.conf
server {
    listen 80;
    server_name example.com;

    location / {
        add_header 'Access-Control-Allow-Origin' 'https://allowed-site.com';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';

        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        proxy_pass http://backend_server;
    }
}

This config sets up a server listening on port 80 for example.com.

The add_header lines tell browsers which origins, methods, and headers are allowed for cross-site requests.

The if block handles preflight OPTIONS requests by responding quickly with no content and caching instructions.

The proxy_pass sends requests to the backend server.

Commands
Check the nginx configuration file for syntax errors before applying it.
Terminal
sudo nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload nginx to apply the new CORS configuration without stopping the server.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
Send a preflight OPTIONS request to check if CORS headers are correctly returned.
Terminal
curl -i -X OPTIONS https://example.com/ -H "Origin: https://allowed-site.com" -H "Access-Control-Request-Method: POST"
Expected OutputExpected
HTTP/1.1 204 No Content Server: nginx Date: Wed, 01 Jan 2025 12:00:00 GMT Content-Type: text/plain; charset=UTF-8 Content-Length: 0 Access-Control-Allow-Origin: https://allowed-site.com Access-Control-Allow-Methods: GET, POST, OPTIONS Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Max-Age: 1728000
-X OPTIONS - Send an OPTIONS request to test preflight CORS
-H "Origin: https://allowed-site.com" - Set the Origin header to simulate a request from allowed-site.com
Send a normal GET request with Origin header to verify CORS headers are present.
Terminal
curl -i https://example.com/ -H "Origin: https://allowed-site.com"
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Date: Wed, 01 Jan 2025 12:00:00 GMT Content-Type: text/html Content-Length: 612 Access-Control-Allow-Origin: https://allowed-site.com <html>...</html>
-H "Origin: https://allowed-site.com" - Set the Origin header to simulate a request from allowed-site.com
Key Concept

If you remember nothing else from this pattern, remember: CORS headers must be sent by the server to tell browsers which websites can access its resources safely.

Common Mistakes
Not handling OPTIONS preflight requests in nginx
Browsers send OPTIONS requests before actual requests to check permissions; if not handled, requests fail.
Add a block in nginx config to respond to OPTIONS requests with proper CORS headers and status 204.
Setting Access-Control-Allow-Origin to '*' when credentials are needed
Browsers block requests with credentials if the origin is '*'.
Set Access-Control-Allow-Origin to the exact allowed domain instead of '*'.
Forgetting to reload nginx after changing config
Changes won't take effect until nginx reloads the config.
Run 'sudo systemctl reload nginx' after editing the config file.
Summary
Write nginx config to add CORS headers and handle OPTIONS preflight requests.
Test config syntax with 'nginx -t' before applying changes.
Reload nginx to apply new settings without downtime.
Use curl with OPTIONS and Origin headers to verify CORS behavior.