13

I have CORS working well with Nginx. The APIs are designed to send non HTTP 200 status code, for example, 401, 404, etc., in case of bad input. The problem is that Chrome cancels/abort the request if it receives a non HTTP 200 status code. Due to this reason, I am not able to show the exact error on the Web client.

What is the way around for CORS non 200 status code errors?

Matze
  • 5,100
  • 6
  • 46
  • 69
Sameer Segal
  • 21,813
  • 7
  • 42
  • 56

2 Answers2

17

By default Nginx only adds headers for requests it considers successful. You can make it add the header without regard for the response code, by adding the always parameter to your add_header directive, e.g.

add_header 'Access-Control-Allow-Origin' '*' always;

Adding the always parameter to the Access-Control-Allow-Origin header is not enough. The always parameter needs to be added to the headers that need to be always added. In some cases, you will need to add the always parameter to the Access-Control-Allow-Credentials header.

add_header 'Access-Control-Allow-Credentials' 'true' always;
Matze
  • 5,100
  • 6
  • 46
  • 69
  • It gives error: `nginx: [emerg] invalid number of arguments in "add_header" directive in /etc/nginx/include.d/cors:37` – Alireza Dec 05 '18 at 06:34
  • This is probably too late, but which version of nginx are you using? The `always` keyword was added in v1.7.5. For earlier versions you will have to use `more_set_headers` as mentioned bellow. – Rune T. Sørensen Jul 22 '19 at 12:25
1

You need to use the more_set_headers module.

with -s you can scpecify more status code

more_set_headers -s '404,400,403' 'Access-Control-Allow-Origin: http://domain.com';

However if you don't have installed this module in nginx you need to recompile it. to compile it :

wget http://nginx.org/download/nginx-1.7.8.tar.gz
git clone https://github.com/openresty/headers-more-nginx-module.git
tar -xzvf nginx-1.7.8.tar.gz
cd nginx-1.7.8
./configure --prefix=/opt/nginx --add-module=/path/to/headers-more-nginx-module
make
make install
llazzaro
  • 3,970
  • 4
  • 33
  • 47