Jayson Lane
Jayson Lane

Reputation: 2828

Rack Rewrite before force_ssl Rails > 3.2 Heroku

I'm using Rack Rewrite to 301 redirect my apex/root domain to my www domain because my wildcard SSL doesn't support the root domain. I'd also like to force SSL sitewide but can't seem to get my rewrite to occur before the force SSL. I've tried a few things, namely the response in this answer: https://stackoverflow.com/a/8217170/535632

Here's my rewrite code:

Gospot::Application.config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do

    if Rails.env.production?
        r301 %r{.*}, Proc.new {|path, rack_env| "http://www.#{rack_env['SERVER_NAME']}#{path}" }, 
                :if => Proc.new {|rack_env| rack_env['SERVER_NAME'] == 'mydomain.com'}
    end
end

I've tried:

require 'rack/ssl'
Gospot::Application.config.middleware.insert_before(Rack::SSL, Rack::Rewrite) do

Instead of using config.force_ssl = true in production.rb but I get the following error on Heroku:

No such middleware to insert before: Rack::SSL (RuntimeError)

Is there anyway to run my rack rewrite before the force_ssl? I've found a lot of answers but they all seem to work for Rails < 3.1

Upvotes: 0

Views: 622

Answers (3)

Uri Klar
Uri Klar

Reputation: 3988

I had the same problem (Rails 3). Apparently force_ssl adds Rack:SSL to the top of the middleware. To insert before it you have to add it as a string or else you will get an "uninitialized constant" error.

Here is the code I ended up using:

SM::Application.config.middleware.insert_before("Rack::SSL", Rack::Rewrite) do
  # rewrite code
end

Upvotes: 0

Dave Brace
Dave Brace

Reputation: 1809

I ran into the same issue where I wanted to use rack-rewrite to redirect based on the domain before forcing SSL. I was able to accomplish this in Rails 4 by inserting the Rack::Rewrite middleware before ActionDispatch::SSL as shown in the code below.

config.middleware.insert_before(ActionDispatch::SSL, Rack::Rewrite) do 
  # redirects / rewrites here
end

Upvotes: 3

Veraticus
Veraticus

Reputation: 16064

The easiest way to do this, depending on your DNS provider, would make your apex DNS record a CNAME for your www subdomain.

If that won't work for you, then you should find a middleware that does exist in your stack to place this rewrite before. Try this:

heroku run rake middleware

To get an idea of what your middleware stack looks like. Choose a piece of middleware that's relatively high up the chain and place the rewrite before it. There's definitely some guess and check that will be going on here, probably, but this will eventually correct your problem.

Upvotes: 1

Related Questions