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!

4 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

@Lorin_Thwaits, that worked perfectly!

For future viewers:

  1. I copied the original source into lib/assume_ssl.rb.
  2. In config/production.rb I added the import: require 'assume_ssl', and in the config block, I added:
ActiveSupport.on_load(:before_initialize) do |app|
    app.config.middleware.insert_before(::Rack::Sendfile, ActionDispatch::AssumeSSL)
  end

That did the trick.

Thanks!

3 Likes

Is this what makes my staging server, which is on port 80 hang up saying

couldn't find https://mystaging.server

when I try to access it?

I found I could get to /home with out any problem

Setting it to false and see what happens!

It works on port 80 setting to false - spent half a moringing wondering why upgrading to 7.1 killed my staging server. I think my 7.0 version had a different staging config.