LoginSignup
42

More than 5 years have passed since last update.

サブディレクトリで Rails アプリを分けるための nginx の設定

Posted at

環境

サーバー: Gehirn RS2
Ruby: 2.0.0p0
Rails: 4.0.0.beta1
nginx: 1.2.7
unicorn: 4.6.2

やりたいこと

Gehirn の初期ドメインは user_name.gehirn.ne.jp となっている。
ここで user_name.gehirn.ne.jp/rails_app のURIアクセスがあったとき public_html/rails_app 以下に飛ぶように nginx を設定する方法を述べる。

事前準備

この記事を参考に以下の作業をしておきます。
http://qiita.com/items/c1edfa84b34dba2211ac

  • 公開鍵の登録
  • データベースの作成
  • Ruby のインストール ($ rs2 install rubyで大丈夫です)
  • nginx のインストール
  • unicorn のインストール (Rails プロジェクトを作成してからの作業です)

nginx の設定ファイル編集

上記参考URLとの違いは以下です。
unicorn 用の設定ファイルにおいてUNIXソケットを使うようにしています。

gehirn-unicorn.conf
upstream backend-unicorn {
    server unix:/home/user_name/public_html/rails_app/tmp/sockets/backend-unicorn.sock;
}

server {
    listen       61***; # Gehirn のプロキシ先ポート番号
    server_name  localhost;

    location /rails_app/ {
        proxy_pass_header Server;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 75; # unicorn設定ファイルのtimeoutも忘れずに
        proxy_pass http://backend-unicorn; # upstreamで定義したバックエンド
    }
}

nginx の設定ファイルは以上です。

unicorn の設定ファイル編集

unicorn の設定ファイルは以下のようにします。

unicorn-conf.rb
$timeout = 75
listen "/home/user_name/public_html/rails_app/tmp/sockets/backend-unicorn.sock"
worker_processes 2
pid "/home/user_name/public_html/rails_app/tmp/pids/unicorn.pid"

Rails アプリのルーティング設定

RAILS_ROOT に config.ru というファイルがあるのでそれを編集するか削除します。
削除したら unicorn がよきに計らってくれるのできちんと動作しますが環境によっては動かないかもしれません。

config.ru
# This file is used by Rack-based servers to start the application.

require ::File.expand_path('../config/environment',  __FILE__)
if ENV['RAILS_RELATIVE_URL_ROOT']
  map ENV['RAILS_RELATIVE_URL_ROOT'] do
    run RailsApp::Application
  end
else
  run RailsApp::Application
end

unicorn の起動

unicorn を起動する際オプションで以下をつけます。
--path がポイントです。自分はこれのせいでかなり時間をとられました。
$ unicorn_rails -c config/unicorn-conf.rb -D --path /rails_app

--pathconfig.ruENV['RAILS_RELATIVE_URL_ROOT'] に入ります。

確認

これで user_name.gehirn.ne.jp/rails_app にアクセスしたら Rails アプリが起動しているはずです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42