LoginSignup
0
0

More than 3 years have passed since last update.

mod rewrite だけを使って、railsをサブフォルダで動かす。

Last updated at Posted at 2018-09-14

PHPとかが動いてるサーバーで、apache passengerとか使うのが少々面倒なときにサクッとrailsを動かしたいときのメモ。

前提

  • Apache 2.4 (with mod_rewrite)
  • ruby 2.4
  • rails 5.2
  • pumaとか

方法

apacheのドキュメントルートの適当なフォルダを作成
mkdir /var/www/html/rails_app

そのフォルダに.htaccessを配置、内容は

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} index\.(html|php)

# ルートディレクトリ用
RewriteRule ^index\.(html|php)$ http://localhost:3000/rails_app [QSA,P,L]

# サブディレクトリ用
RewriteRule ^(.*)/index\.(html|php)$ http://localhost:3000/rails_app/$1 [QSA,P,L]

# for assets
RewriteCond %{REQUEST_URI} \.(css|js|ico)$
RewriteRule ^(.*)$ http://localhost:3000/$1 [QSA,P,L]

RewriteCond %{REQUEST_URI} ^/rails_app
RewriteRule ^(.*)$ http://localhost:3000/rails_app/$1 [QSA,P,L]

もちろんポート番号、サブフォルダ名は任意に変更。

あと、config/environment.rbにサブフォルダ用として、
[rails app name]::Application.routes.default_scope = "/rails_app"
の一文を追加。

仕組みとしては、mode_rewriteでrails serverにforwardしている。
そのままだとrailsはサブフォルダがつかないルーティングをするので、environment.rbで変更。

あとはアセットパスとかがそのままだったりするので、これもうまくforward
(このへんうまく調整できそうなもんだけどなかなかうまく行かなかった。railsのサブフォルダのやり方簡単にならんかな…)

あとはrails sでサーバーを起動させておくだけ。
これでちゃんとrailsの画面が表示されるはず。

もしされなかったら、rewriteルールがうまくいってない可能性があるので、
rewriteのログを出してみてもいい。

httpd.conf
LogLevel rewrite:trace8

これを追記すればエラーログにrewriteのログが出てくる。(ちょっとわかりにくいログだけど)

0
0
0

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
0
0