How do I configure `Access-Control-Allow-Origin` with rails, nginx and passenger?

YES! Finally.

user664833's answer above is great, except I couldn't find my Passenger config file to edit.

Thomas Nye's answer here gives the full file to create at config/nginx.conf.erb:

    ##########################################################################
#  Passenger Standalone is built on the same technology that powers
#  Passenger for Nginx, so any configuration option supported by Passenger
#  for Nginx can be applied to Passenger Standalone as well. You can do
#  this by direct editing the Nginx configuration template that is used by
#  Passenger Standalone.
#
#  This file is the original template. DO NOT EDIT THIS FILE DIRECTLY.
#  Instead, make a copy of this file and pass the `--nginx-config-template`
#  parameter to Passenger Standalone.
#
#  Learn more about using the Nginx configuration template at:
#  https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template
#
#  *** NOTE ***
#  If you customize the template file, make sure you keep an eye on the
#  original template file and merge any changes. New Phusion Passenger
#  features may require changes to the template file.
##############################################################

<%= include_passenger_internal_template('global.erb') %>

worker_processes 1;
events {
    worker_connections 4096;
}

http {
    <%= include_passenger_internal_template('http.erb', 4) %>

    ### BEGIN your own configuration options ###
    # This is a good place to put your own config
    # options. Note that your options must not
    # conflict with the ones Passenger already sets.
    # Learn more at:
    # https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template

    ### END your own configuration options ###

    default_type application/octet-stream;
    types_hash_max_size 2048;
    server_names_hash_bucket_size 64;
    client_max_body_size 1024m;
    access_log off;
    keepalive_timeout 60;
    underscores_in_headers on;
    gzip on;
    gzip_comp_level 3;
    gzip_min_length 150;
    gzip_proxied any;
    gzip_types text/plain text/css text/json text/javascript
        application/javascript application/x-javascript application/json
        application/rss+xml application/vnd.ms-fontobject application/x-font-ttf
        application/xml font/opentype image/svg+xml text/xml;

    <% if @app_finder.multi_mode? %>
        # Default server entry for mass deployment mode.
        server {
            <%= include_passenger_internal_template('mass_deployment_default_server.erb', 12) %>
        }
    <% end %>

    <% for app in @apps %>
    server {
        <%= include_passenger_internal_template('server.erb', 8, true, binding) %>
        <%# <%= include_passenger_internal_template('rails_asset_pipeline.erb', 8, false) %1> %>

        ### BEGIN your own configuration options ###
        # This is a good place to put your own config
        # options. Note that your options must not
        # conflict with the ones Passenger already sets.
        # Learn more at:
        # https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template
        # Rails asset pipeline support.
        location ~ "^/assets/.+-([0-9a-f]{32}|[0-9a-f]{64})\..+" {
            error_page 490 = @static_asset;
            error_page 491 = @dynamic_request;
            recursive_error_pages on;

            if (-f $request_filename) {
                return 490;
            }
            if (!-f $request_filename) {
                return 491;
            }
        }
        location @static_asset {
            gzip_static on;
            expires max;
            add_header Cache-Control public;
            add_header ETag "";
            if ($http_origin ~* ((https?:\/\/[^\/]*\.herokuapp\.com(:[0-9]+)?))) {
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, HEAD';
                add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
            }
        }
        location @dynamic_request {
            passenger_enabled on;
        }

        ### END your own configuration options ###
    }
    passenger_pre_start <%= listen_url(app) %>;
    <% end %>

    <%= include_passenger_internal_template('footer.erb', 4) %>
}

Procfile should include the line:

web: bundle exec passenger start -p $PORT --max-pool-size 3 --nginx-config-template config/nginx.conf.erb

You'll also need to configure you Cloudfront CDN that is serving the assets as per Guapolo's answer

Configure CORS Cloudfront

In your distribution that is giving you the CORS grief, go to the behaviours tab, and a new behaviour, selecting the path to the asset, i.e. /assets/icons.ttf and whitelist 'Origin' as per the above image.

You may also need, in you distribution, to 'invalidate' the old cached resource, in the invalidations tab, i.e. put in the full asset and cached name from your inspector, and invalidate. Once that has processed, deploy the app with the config and restart heroku. You'll need to open inspector and 'empty cache and hard reload' the page.

Hopefully that works - it sounds like the passenger config changes every now and then, so we may find this breaks and the answer will need to be updated to reflect the new config.


The Server line made me think that perhaps the assets are not being handled by Rails, but rather by nginx:

enter image description here

This means that the headers must be added by nginx, not Rails, and therefore we need to configure nginx. It turns out that the ability to configure nginx is possible as of Passenger 4.0.39 - (here is the corresponding Git diff). The corresponding documentation is available in Passenger Standalone, under Advanced configuration.

An important note in the documentation: The original configuration template file may change from time to time, e.g. because new features are introduced into Phusion Passenger. If your configuration template file does not contain the required changes, then these new features may not work properly. In the worst case, Standalone might even malfunction. Therefore, every time you upgrade Phusion Passenger, you should check whether the original configuration template file has changed, and merge back any changes into your own file.

With respect to that note, in addition to the customizable copy of the configuration file, create an "original" copy that you can diff whenever you upgrade Passenger.

bash

cp $(passenger-config about resourcesdir)/templates/standalone/config.erb config/nginx.conf.erb
cp config/nginx.conf.erb config/nginx.conf.erb.original

Next, add --nginx-config-template config/nginx.conf.erb to the web line in Procfile.

Procfile

web: bundle exec passenger start -p $PORT --max-pool-size 3 --nginx-config-template config/nginx.conf.erb

config/nginx.conf.erb

Next, edit the configuration file config/nginx.conf.erb by finding a block that looks as follows:

    location @static_asset {
        gzip_static on;
        expires max;
        add_header Cache-Control public;
        add_header ETag "";
    }

...and add the two Access-Control lines:

    location @static_asset {
        gzip_static on;
        expires max;
        add_header Cache-Control public;
        add_header ETag "";
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Request-Method *;
    }

That's it. This will work in production, but not in development, due to config.assets differences between the two.

the config diff

The diff should not return anything now, but if any future updates to passenger include a change to this file, you will know.

diff $(passenger-config about resourcesdir)/templates/standalone/config.erb config/nginx.conf.erb.original

nginx documentation

  • http://nginx.org/en/docs/beginners_guide.html
  • http://nginx.org/en/docs/http/ngx_http_core_module.html#location

future improvements

  • restrict the Allow-Origin
  • restrict the Request-Method
  • restrict both headers to just fonts

I'm not sure that it is answer, but it looks like you also could try the easiest way with using after_filter with:

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
...