Still get data even there is a CORS issue in Nginx

devwannabe asked:

I’m trying to debug a CORS issue. Here’s my configuration
I’m using to test my Nginx rules.
I get the message below in my browser’s console when the method I use is OPTIONS. But I still received the data which is very weird

Failed to load Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

I get the message below if the method I use is GET. I also get the data

Failed to load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

Here’s my updated nginx configuration, 3rd update and I put it on a new file.

  ❯ cat /usr/local/etc/nginx/nginx-mini.conf
  worker_processes  1;
  worker_rlimit_nofile 15000;

  error_log  logs/error.log;
  error_log  logs/error.log  notice;
  error_log  logs/error.log  info;

  events {
   worker_connections  5000;
   accept_mutex off;

  http {
   include       mime.types;
   default_type  application/octet-stream;
   proxy_cookie_path / "/; HTTPOnly; Secure";

   types_hash_max_size 4096;
   access_log off;
   sendfile off;
   sendfile_max_chunk 512k;
   tcp_nopush      off;
   tcp_nodelay      on;
   output_buffers 1 3m;

   open_file_cache          max=10000 inactive=5m;
   open_file_cache_valid    2m;
   open_file_cache_min_uses 1;
   open_file_cache_errors   on;

   gzip on;
   gzip_disable "MSIE [1-6]\.(?!.*SV1)";
   gzip_http_version  1.1;
   gzip_comp_level    5;
   gzip_min_length    256;
   gzip_proxied       any;
   gzip_vary          on;


   # CORS
   map $http_origin $allow_origin {
     default ""; "$http_origin";

   server {
     listen 8009;
     access_log /var/log/nginx/access.log;
     error_log /var/log/nginx/error.log debug;

     location /testcors {
        if ($request_method = 'OPTIONS') {
           add_header 'Access-Control-Allow-Origin' $allow_origin;
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
           add_header 'Access-Control-Max-Age' 60;
           add_header 'Content-Type' 'text/plain; charset=utf-8';
           add_header 'Content-Length' 0;
           return 204;
        if ($request_method = 'POST') {
           add_header 'Access-Control-Allow-Origin' $allow_origin;
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
           add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

        if ($request_method = 'GET') {
           add_header 'Access-Control-Allow-Origin' $allow_origin;
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
           add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
           add_header GETMETHOD accessed;
           add_header Content-Type "application/json; charset=utf-8";

       add_header Content-Type "application/json; charset=utf-8";
       return 200 '{"code": 200, "reason": "Testing CORS ..."}';

I started it this way

sudo nginx -c /usr/local/etc/nginx/nginx-mini.conf

ps ax | grep nginx shows the process

31528   ??  Ss     0:00.00 nginx: master process nginx -c /usr/local/etc/nginx/nginx-mini.conf
31529   ??  S      0:00.00 nginx: worker process
31787 s003  R+     0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn nginx

netstat shows the tcp port associated with my nginx

❯ netstat -na|grep 8009
tcp4       0      0  *.8009                 *.*                    LISTEN

The ip address is correct

 ❯ ping
 PING ( 56 data bytes
 64 bytes from icmp_seq=0 ttl=64 time=0.042 ms
 64 bytes from icmp_seq=1 ttl=64 time=0.067 ms
 64 bytes from icmp_seq=2 ttl=64 time=0.132 ms

I made sure I’m connecting to my own locally running nginx server using curl

❯ curl
{"code": 200, "reason": "Testing CORS ..."}%

And the results are still the same(screenshots of chrome dev tools)

My answer:

The problem is that you are not sending CORS headers in your location /testcors.

You only send these in the server block, for any other location.

The reason for this is that add_header directives in lower level blocks completely override those in higher level blocks. So, because you have used add_header in your location, you must also include all the other add_header directives again.

To keep your configuration DRY, you should consider making an include file which contains the common add_header directives, and then include it at each relevant point in the configuration.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.