I am trying add CORS directive to my nginx file for as simple static HTML site. (taken from here http://enable-cors.org/server_nginx.html)
Would there be a reason why it
add_header
has to be placed under either http
, server
, location
or if in location
block.
You are placing in under if in server
. Move them under the location
block.
server {
listen 8080;
location / {
root /var/www/vhosts/mysite;
if ($http_origin ~* (https?://[^/]*\.domain\.com(:[0-9]+)?)$) {
set $cors "true";
}
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
if ($request_method = 'GET') {
set $cors "${cors}get";
}
if ($request_method = 'POST') {
set $cors "${cors}post";
}
if ($cors = "trueget") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
}
if ($cors = "truepost") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
}
if ($cors = "trueoptions") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 204;
}
}
}
Source: http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header