Rails x nginxでサブディレクトリでアプリケーションを動かす

早速本題。必要なのは以下2点

  1. nginxの設定
  2. config.ruの設定

nginxの設定について

nginxには以下のように記述する。

client_max_body_size 2G;

upstream app_server {
  server unix:/var/www/#{ app directory }/tmp/sockets/unicorn.sock fail_timeout=0; 
}

server {
  listen 80;
  server_name xxx.xx.xx.xxx;
  keepalive_timeout 5;
  try_files $uri/index.html $uri.html $uri @app;
  
  location /#{ sub directory name}/ { #ここ
    error_log  /var/log/#{ app directory }/nginx/nginx.error.log;
    access_log /var/log/#{ app directory }/nginx/nginx.access.log;
    root /var/www/#{ app directory }/public;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://app_server; #ここ ※2
  }

  error_page 500 502 503 504 /500.html;
  location = /500.html {
    root /var/www/#{ app directory }/public; 
  }
}

※2 ここで末尾に「/」を入れないのが肝

rails_app/config.ruの設定について

RAILS_RELATIVE_URL_ROOT='/#{ sub directory name }' # ここは環境変数などにしたほうがよい?

require_relative 'config/environment'


if RAILS_RELATIVE_URL_ROOT then
  map RAILS_RELATIVE_URL_ROOT do
    run Rails.application
  end
else
  run Rails.application
end

以上、簡単にサブディレクトリ切れます。 素敵なサブディレクトリライフを!