Adding CORS header for specific domains in Nginx

(1) Modify location block:

location / {
        set $cors '';
        if ($http_origin ~ '^https?://(calvin\.my|www\.calvin\.my)') {
                set $cors 'true';
        }

        if ($cors = 'true') {
                add_header 'Access-Control-Allow-Origin' "$http_origin" always;
                add_header 'Access-Control-Allow-Credentials' 'true' always;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
                add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Typ$
        }

        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;
        }
}

(2) Reload Nginx

sudo service nginx restart

AI Summary
Chrome On-device AI 2024-12-06 19:13:05

Share Article