株式会社TECH LUCKという会社で代表兼エンジニアをしている齊藤です。
表題の通りですが、Railsアプリケーションで example.com/ec-site
というようなサブディレクトリの形でRailsアプリケーションをリリースしたい時の設定になります。
環境は以下の通りです。
- Nginx
- Ruby on Rails:v7.1
- Ruby:3.2
- puma
この記事では便宜的にドメイン名をexample.com
、アプリケーション名をec-site
という名前にしています。
Nginxの設定
Nginxのファイルを以下のように設定してください。
ただし、example.com
とec-site
に関しては、ご自身の環境に合わせて変更してください。
rails.conf
client_max_body_size 2G;
upstream app_server {
server unix:///var/www/ec-site/current/tmp/sockets/puma.sock;
}
server {
listen 80;
server_name example.com;
keepalive_timeout 5;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
root /var/www/ec-site/current/public;
location ^~ /ec-site/assets/ {
gzip_static on;
add_header Cache-Control public;
}
try_files $uri/index.html $uri @app_server;
location /ec-site/ {
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
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;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
}
location = /sitemap.xml.gz {
}
location = /robots.txt {
}
location = /favicon.ico {
}
}
credentialsに以下の設定を追加
サブディレクトリを変更したいとなった際に、変更が面倒になるので以下のようにcredentialsにサブディレクトリを指定する。
※情報的にcredentialsじゃない方がいいかもしれないので、適宜読み替えてください。
app:
relative_url_root: /ec-site
environmentsファイルへの設定反映
environments/production.rb
とenvironments/development.rb
に以下の設定を追加してください。
environments/production.rb、または、environments/development.rb
# ディレクトリのルートをサブディレクトリに指定
config.relative_url_root = Rails.application.credentials.dig(:app, :relative_url_root)
# assetsの場所をサブディレクトリに指定
config.assets.prefix = "#{Rails.application.credentials.dig(:app, :relative_url_root)}/assets"
config.ruへの設定反映
config.ru
を以下の内容に変更する
config.ru
# This file is used by Rack-based servers to start the application.
require_relative "config/environment"
RAILS_RELATIVE_URL_ROOT = Rails.application.credentials.dig(:app, :relative_url_root)
if RAILS_RELATIVE_URL_ROOT.present? then
map RAILS_RELATIVE_URL_ROOT do
run Rails.application
Rails.application.load_server
end
else
run Rails.application
Rails.application.load_server
end
これでサブディレクトリの設定ができたと思います。
ローカル環境では
localhost:3000/ec-site
というURLで開かれることになります。
参考文献(圧倒的感謝)