Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nkeena's avatar

add_header not taking effect

I've added the following to my etc/nginx/nginx.conf file but I'm still not seeing these response headers in my ajax calls. I've restarted nginx and still nothing. Any ideas?

add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Allow-Methods' 'POST, GET, PUT, DELETE';

proxy_set_header Access-Control-Allow-Origin $http_origin;
0 likes
4 replies
nkeena's avatar

That did the trick! It works but will not work when I try to send an Authorization header with the request. It always returns a 400 HTTP error. Any errors 400 or greater also will not return the headers I added as well.

1 like
andrewtweber's avatar

@nkeena

[add_header] adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307.

If you want the header to be set on 400 level errors, you need to add the "always" keyword:

add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
add_header 'Access-Control-Allow-Methods' 'POST, GET, PUT, DELETE' always;

Source: http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header

1 like
carobiscuit's avatar

@andrewtweber i have been looking for like 3 days for the reason nginx would NOT ACCEPT my access-control header. You are literally the only one who suggested what worked for me: "always".

Please or to participate in this conversation.