How to configure the protocol generated by built-in URL helpers in Rails?

60 Views Asked by At

In production, my Rails app (Rails 7.0) is behind a CDN, which handles SSL. SSL terminates at the CDN before sending requests within my private VPC to my application, which is configured to be unsecured, since it's not exposed to the public internet.

For the most part, this doesn't affect Rails URL helpers - as long as I use path helpers instead of URL helpers to navigate the site, it maintains the https protocol across the links. However, there are some places in Rails, e.g. the ActiveStorage direct upload library, where Rails has hardcoded the use of an internally-generated URL helper (specifically rails_direct_uploads_url). Since my app is configured to be unsecured internally, these URLs are generated with the http:// protocol, and most browsers reject requests made to them due to security settings. This breaks direct uploads entirely, and I can't find a way to alter how those URLs get generated, since I don't have access to the routes config for them.

I've tried setting the default URL options (Rails.application.routes.default_url_options[:protocol] = 'https'), which didn't affect the URL generated.

I've tried updating the defaults in the route object directly in an initializer, as below:

ActiveSupport.on_load(:action_controller) do
  Rails.application.routes.named_routes.get(:rails_direct_uploads).defaults[:protocol] = 'https'
end

It seems like they're generated dynamically for each request, maybe? This causes the helpers to generate HTTPS URLs when I do it in the console, but doesn't change the URL generated on the actual page when I run it in the application via an initializer.

Setting default_url_options in ActionController doesn't work for this, since internal Rails controllers don't inherit from ActionController.

0

There are 0 best solutions below