前書き
webアプリケーションにて複数のアプリケーションをURLだけ変更し同一ポート(80番)で運用したい場合がある
例えば下記のような形だ
http://exsample.com #=>アプリ1つ目
http://exsample.com/hoge1 #=>アプリ2つ目
http://exsample.com/hoge2 #=>アプリ3つ目
fqdn以降のURLが違う、サブディレクトリでの運用となる
今回は上記をsinatraでやる方法を紹介します。
以前別の記事↓でも紹介した方法でも可能ですがもっといい方法が見つかったため、新規で紹介します。
nginx+puma+sinatra サブディレクトリ、unixソケット構成(ポートなんぞ使わん)
File構成
/var/www/
app/
├ config/puma.rb
├ log/*.log
├ tmp/
│ ├ pids/puma.pid
│ └ sockets/puma.sock
├ config.ru ★
├ app.rb
└ api.rb
※bundle系ファイル略
ファイル構成はおおよそ前回と差分はない、api用のsinatra記述はファイルを分けたかったため、別ファイルとしている、注目は★マークがついてるconfig.ruというrubyでwebサーバー機能を提供している
Rackの設定ファイルをいじることでサブディレクトリでの運用の実現が可能となる。
↓Rackについては下記記事がわかりやすかったです。
Rack解説 - Rackの構造とRack DSL
アプリ構成
http://exsample.com/hoge #=> メインページ
http://exsample.com/hoge/api #=> API用URL
上記構成を作っていきます。
sinatra設定
sinatra側のファイルを作成します。
メインページ
require "sinatra/base"
class App < Sinatra::Base
set :server, :puma
get "/" do
"hello world"
end
get "/redirect" do
redirect to("dest")
end
get "/dest" do
"yattaze"
end
end
API用URL
require "json"
require "sinatra/base"
class Api < Sinatra::Base
set :server, :puma
get "/" do
content_type :json
response = {test: "hogege"}
response.to_json
end
end
今回APIページはアクセスしたらjsonを返すようにする。
Rack設定
サブディレクトリ運用のため、Rack設定ファイルでmapを使用する
require_relative "app"
require_relative "api"
root_path = '/hoge'
map(root_path){run App} #=> メインページへのアクセス設定
map(root_path + '/api'){run Api} #=> API用URLへのアクセス設定
Puma設定
特に前回と差分ないので下記参照
nginx+puma+sinatra サブディレクトリ、unixソケット構成(ポートなんぞ使わん)
nginx設定
rewriteがいらなくなりました。
location /hoge {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
#puma unix socket
proxy_pass http://unix:/var/www/app/tmp/sockets/puma.sock;
}
サービス起動で無事、サブディレクトリ運用完成