Share

Running a Rails 3 Application in a Sub-URI Enviroment

Sometimes you need to run your Rails (3) Application on a Sub-URI (e.g. examle.com/prod, example.com/dev). In my current Project there was a Problem with that Configuration and the Rails url-helpers (link_for, url_for, usw.) becourse the app wasn’t aware of the necessary prefix (in our example “/dev”, “/prod”).

There is always the possibility to set the apps basic URL within your app-Context. Together with setting the prefix in a System Enviroment it was possible to achieve the wanted app behaviour.
How to configure a Rails3 App with Passenger in a Sub-URI Configuration please have a look in the Phusion Passenger users guide here or in another blog post here.

The Basic Apache Configuration looks somehow like this:

<VirtualHost *:80>
    ServerName      example.com
    ServerAdmin     admin@example.com
    DocumentRoot    /var/www
    # we added two file hardlinks from our apps public folder to /var/www/dev,  /var/www/prod
        <Directory /var/www/prod>
        ...
        SetEnv RAILS_RELATIVE_URL_ROOT /prod
        ...
    </Directory>
        <Directory /var/www/dev>
        ...
        SetEnv RAILS_RELATIVE_URL_ROOT /dev
        ...
    </Directory>
</VirtualHost>

The last part is to add a Before-Hook to the ApplicationController for updating the apps default_url if RAILS_RELATIVE_URL_ROOT is set:

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :action_set_url_options

  def action_set_url_options
    if ENV['RAILS_RELATIVE_URL_ROOT']
      @host = request.host+":"+request.port.to_s+"/"+ENV['RAILS_RELATIVE_URL_ROOT']
    else
      @host = request.host+":"+request.port.to_s
    end
    Rails.application.routes.default_url_options = { :host => @host}
  end
end

You may also like...

Leave a Reply