Sometimes you may want to deploy a Rails application to sub-uri. But it's not seamless if you didn't write your code carefully. The main problem is absolute url.

Avoid absolute url

By default, Rails application only work under root uri unless properly configured. And (maybe) most developers are supposing that the application will be deployed under root uri when writing code. So absolute url is widely used, and they break when deployed under sub-uri. So we should avoid using absolute url. Use relative url or url helpers instead. The are two types of url in Rails: asset url and route url.

Asset url

Since most Rails applications are using Rails Asset Pipeline to manage assets, asset urls are usually generated by asset url helpers like asset_path, asset_url, image_path, etc. These helpers will take care of sub-uri for you if you have configured properly. (See AssetUrlHelper for more helpers and their usage. These helpers are available in view layer. To use them in other places, prefix them with ActionController::Base.helpers.) However, if you put assets directly under public folder, then it's your own responsibility to take care of sub-uri. In such case, use relative url or prefix with Rails.configuration.relative_url_root.

Asset Pipeline

You must set RAILS_RELATIVE_URL_ROOT environment variable when precompiling assets, otherwise url generated by url helpers (such as image-url in scss) would not include sub-uri.

RAILS_RELATIVE_URL_ROOT=/sub-uri bundle exec rake assets:precompile

If you use some deployer (such as mina, capistrano) to automatically precompile assets in production environments, then you should refer to the deployer's documentation about how to pass environment variables to precompiling task. For mina 0.3.x, you can set env_vars in your deploy.rb:

set :env_vars, 'RAILS_RELATIVE_URL_ROOT=/sub-uri'