Skip to content

ActionMailer link for a Rails app deployed in a sub-directory

I’ve just deployed a Ruby on Rails application in a sub-directory of a client’s website.   So rather than accessing the app at www.example.com, you need to visit www.example.com/app.  This was quite easy using an extra couple of lines in config.ru.

if Rails.env.production?
  map '/app' do
    run MyApp::Application
  end
else
  run MyApp::Application
end

This handles updating URLs generated by link helpers, but only in production. That lets us still access the app at localhost:3000 without having to type the /app.

However, when used in an ActionMailer template, my links were missing the /app prefix.  After a bit of head-scratching and frantic Googling I discovered the :script_name parameter in the default URL options. Pop the following in your production.rb environment file.

config.action_mailer.default_url_options = {
    :host => "www.example.com",
    :protocol => 'https',
    :only_path => false,
    :script_name => "/app"
}

This will result in URLs that look like https://www.example.com/app/my_route. Perfect.