Skip to content

Instantly share code, notes, and snippets.

@mars
Created August 17, 2023 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mars/b6db4a359e336be9b654a361e7833426 to your computer and use it in GitHub Desktop.
Save mars/b6db4a359e336be9b654a361e7833426 to your computer and use it in GitHub Desktop.
Rails unified host override for use with apps behind a CDN (Rack middleware, supports OmniAuth)
# Rack middleware that reads environment variable HOST (value such as: app.example.com)
# to override request Host headers, forcing the app to use this value for URLs & redirects.
#
# If env var HOST is unset, then this middleware does nothing.
#
# Useful for when a Rails app is the origin behind a CDN/proxy, so that all generated
# URLs point to the canonical hostname of the CDN, and not the origin itself.
#
# For a Rails app,
# - save this file in config/initializers/set_default_host.rb
# - set YourRailsAppModuleName to the app's module name (see config/application.rb)
#
module YourRailsAppModuleName
class SetHostMiddleware
def initialize(app)
@app = app
@new_host = ENV['HOST']
end
def call(env)
if @new_host
env[:Host] = @new_host
env[:default_host] = @new_host
env["HTTP_HOST"] = @new_host
end
@app.call(env)
end
end
class Application < Rails::Application
config.middleware.insert_before(Rack::Runtime, SetHostMiddleware)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment