Skip to content

Instantly share code, notes, and snippets.

@shad1w
Last active April 22, 2024 23:12
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shad1w/75e7ebbbdc5382719cd06f56bbe6acd0 to your computer and use it in GitHub Desktop.
Save shad1w/75e7ebbbdc5382719cd06f56bbe6acd0 to your computer and use it in GitHub Desktop.
Deploying a rails application in a subdirectory

Making a Rails application deployable in a subdirectory

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.

Prerequisites

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.

Modifying the app

We will now modify our app to take into account the environment variable MYAPP_RELATIVE_URL_ROOT.

Routes

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

Fixing assets

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]

Starting the app

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.

@mesge
Copy link

mesge commented Jul 7, 2017

What does your nginx conf look like?

@shad1w
Copy link
Author

shad1w commented Aug 21, 2017

@mesge Unfortunately I didn't test this with NGINX yet.

The only thing that I thoroughly tested so far is serving assets from the rails server itself and then having an apache webserver set up as a reverse proxy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment