Railsで静的ファイルをcontroller経由で配信する
目的
- 特定の理由でpublic以下の静的ファイルをunicornでサーブする必要がある
前提
- 本番ではpublic以下をnginxやapacheでサーブしている
- 本番のconfigureをいじって全体に影響する設定を書き換えるのは嫌
本番のconfigure
config.serve_static_files = false
・・ということでcontrollerで静的ファイルをrenderする方法です。
class StaticController < ApplicationController def index render file: 'public/static.html', status: 200, layout: false end end
設定の問題か、これだとレスポンスヘッダにLast-Modifiedが付与されないので少し追記。
class StaticController < ApplicationController def index stat = File::stat("#{Rails.root}/public/static.html") response.headers['Last-Modified'] = stat.mtime.gmtime.strftime("%a, %d %b %Y %H:%M:%S GMT") render file: 'public/static.html', status: 200, layout: false end end
こんな感じでOK!