How to config subdirectory with Rails + Nginx + Unicorn ?

29Mar, 2019

This article mainly focus on how to run rails app in subdirectory using NGINX. You will learn reverse proxy of nginx to serve your rails app.

It was needed because I came to meet a problem in which I want to run specific part of a website in Ruby on Rails for specific subdirectory.  For example my website is in PHP and I want to run Ruby on rails site on the same url with different subdirectory like Whenever /runthisinrubyonrails/ detected, It should run on different server which is running   ROR. 


Configuration in rails app.

Rails give us simple configuration for this purpose.

In config/application.rb file, add the following code:

module YourAPPName
  class Application < Rails::Application
    config.relative_url_root = '/runthisinrubyonrails'
    # some other configuration code

In file:

map Rails::Application.config.relative_url_root || "/" do
  run Rails.Application

Test everything works fine

we can check everything works fine with click route with /runthisinrubyonrails/ and simple by /.

for example first asset was getting by now you can try with Both should work because when we have defined that in our file

Rails::Application.config.relative_url_root || "/"

if relative_url_root found then try with that if not then try with “/”

Nginx Configuration

So we have the following configuration:

upstream unicorn_sock {
  server your_sock_path;

server {
root <path_to_your_rails_app>/public;
location @proxy_rails_app {
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $http_host;
  proxy_redirect off;
  proxy_pass http://unicorn_sock;
location /runthisinrubyonrails/ {
  alias <path_to_your_rails_app>/public/;
  try_files $uri @proxy_rails_app;
try_files $uri @proxy_rails_app;
# some other configuration code