Rails3 css、js 404 Not Found! 静的ファイルが読み込まれない!

検証環境(VM)でアプリを実行したところ、js、css、イメージファイルなどの静的ファイルが読み込まれず、404 Not Foundになってしまいました。

これの原因は、config/environments/production.rb内の設定で、config.serve_static_assetsの値がプロダクション環境ではデフォルトでfalseになっているためでした。

# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false


Rails guideによると、この値は静的ファイルをRails自身がサーブするか、NginxやApacheなどのアプリケーションがサーブするかでtrueとfalseを切り替えます。静的ファイルはNginxやApacheが供給すべきなのでプロダクションモードのテストの時など以外にはtrueにしないでね。ということらしいです。
今回は自分しか使わないVMだったのでtrueにしましたが、プロダクション環境ではNginxやApacheのconfファイルで設定しましょう。

config.serve_static_assets configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won´t be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app.


参考:
http://guides.rubyonrails.org/configuring.html