Rails 7.1's config.assume_ssl for Rails 7.0

Is there a way to port the config.assume_ssl functionality from 7.1 alpha to 7.0.4.3? I’ve an app working well, and I woud like to incorporate only that feature to 7.0.4.3. Any help or idea on how to do it? Tks!

1 Like

I guess, this is the code to implement this behaviour.

1 Like

Sure enough – that’s the stuff! You can add this to pretty much any older version of Rails by modifying your application.rb to look like this:

module TestApp
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 7.0

    # Configuration for the application, engines, and railties goes here.
    ...
    (all your other normal config settings and such)
    ...

    # After upgrading to Rails 7.1 or later, trade this out for:  config.assume_ssl = true
    ActiveSupport.on_load(:before_initialize) do |app|
      app.config.middleware.insert_before(::Rack::Sendfile, ::TestApp::AssumeSSL)
    end
  end

  class AssumeSSL
    def initialize(app)
      @app = app
    end

    def call(env)
      env["HTTPS"] = "on"
      env["HTTP_X_FORWARDED_PORT"] = 443
      env["HTTP_X_FORWARDED_PROTO"] = "https"
      env["rack.url_scheme"] = "https"

      @app.call(env)
    end
  end
end

Of course rename TestApp to your real application name.

After everything boots, the middleware stack (shown by running Rails.application.config.middleware) should have this sequence – note that AssumeSSL comes right before Rack::Sendfile:

Eager to hear how you get on!

2 Likes

thank you so much Lorin for taking the time to teach me! I will try it asap and come back to you

1 Like

Works great and also I learnt a lot. Thank you!

1 Like