Prevent nginx from removing CORS headers set by rack-cors

1.1k Views Asked by At

Context

I use Docker to deploy my Rails application with an nginx container as my front HTTP server.

I configured rack-cors in Rails to send CORS headers for some URLs.

My application is available using 2 different domains using HTTPS, configured in nginx as 2 different server configurations. This first one configured as the default_server.

Internal communications between nginx and Rails are using HTTP. HTTPS is only configured in nginx.

To be clear, what I mean by CORS headers are:

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Expose-Headers
  • Access-Control-Max-Age

I am using rack-cors 1.0.2 and nginx 1.16.0.

I created a Gist with my nginx configuration.

Problem

When using the 2nd domain using HTTPS, my CORS headers set by rack-cors are removed by nginx.

I know they are removed because I monitored multiple things:

  • I put rack-cors in debug mode and it correctly outputs the CORS headers in Rails logs.
  • I performed the query directly to Rails from within the nginx container and the response contained the CORS headers.
  • I monitored the query/response made by nginx to Rails using tcpdump and the response contained the CORS headers.

But the response made by nginx to the end user does not contain the CORS headers.

All this time, responses sent for the first domain are OK and contain the CORS headers.

Questions

  • Why is nginx removing those headers from the upstream response?
  • How can I monitor this behavior in nginx?
  • How can I prevent nginx from rewriting these response?

Thanks

1

There are 1 best solutions below

0
Илья Хоришко On

My site.conf

server {
  listen 80;
  server_name localhost;
  sendfile on;

  access_log /var/log/nginx/site.log;

  location /folderWithFiles/ {
        internal;
    set $access_control_expose_headers $upstream_http_access_control_expose_headers;
    set $access_control_allow_origin $upstream_http_access_control_allow_origin;
    set $access_control_allow_credentials $upstream_http_access_control_allow_credentials;
    set $access_control_allow_methods $upstream_http_access_control_allow_methods;
    set $access_control_allow_headers $upstream_http_access_control_allow_headers;

    add_header Access-Control-Expose-Headers $access_control_expose_headers;
    add_header Access-Control-Allow-Origin $access_control_allow_origin;
    add_header Access-Control-Allow-Credentials $access_control_allow_credentials;
    add_header Access-Control-Allow-Methods $access_control_allow_methods;
    add_header Access-Control-Allow-Headers $access_control_allow_headers;

    root /home/ilya/Projects/site/uploads/; 
    #result path /home/ilya/Projects/site/uploads/folderWithFiles/
  }

  location / {
    proxy_pass http://localhost:5252/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}