USE THIS GUIDE AT YOUR OWN RISK! I AM NOT RESPONSIBLE FOR ANYTHING YOU DO BY FOLLOWING THIS GUIDE! IF ANY DAMAGE IS DONE BY FOLLOWING THE INSTRUCTIONS HERE, IT IS ENTIRELY YOUR RESPONSIBILITY AND I MAY NOT BE HELD LIABLE FOR IT!
Using this guide, you can make it possible to put your Ruby on Rails application behind a reverse proxy in a subdirectory.
This guide was written for Rails 5.
Using this method, the environment variable RAILS_RELATIVE_URL_ROOT
should not be set.
Static, precompiled assets can either be served directly using the Rails server or through the reverse proxy. For simplicity, we will serve them through the Rails server in this guide.
To do so, set the environment variable RAILS_SERVE_STATIC_FILES
to true
before running the app.
We will now modify our app to take into account the environment variable MYAPP_RELATIVE_URL_ROOT
.
All routes need to be wrapped in a scope, which defines the root path to serve from:
Rails.application.routes.draw do
scope ENV['MYAPP_RELATIVE_URL_ROOT'] || '/' do
# Routes here
end
end
The change to the routes does not make any changes to the assets. These would still be served relative to /
.
To change this, the following line needs to be added in config/application.rb
config.assets.prefix = "#{ENV['MYAPP_RELATIVE_URL_ROOT']}#{config.assets.prefix}"
Also make sure that images are precompiled. For this, add the following to config/initializers/assets.rb
:
Rails.application.config.assets.precompile += %w[*.png *.jpg *.jpeg *.gif]
Before starting the app, the environment variable MYAPP_RELATIVE_URL_ROOT
should be set to whatever subdirectory the app should be served from.
On a linux server, this would be done by using export MYAPP_RELATIVE_URL_ROOT='/myapp'
If the app should be served from the root directory, this variable doesn't need to be set at all.
Now, the Rails server can be started.
I have in my routes.rb the following part:
direct :account do |model, options|
so the scope is not available here, get an error that direct can't be inside scope