Search code examples
ruby-on-railsmiddleware

Why ActionDispatch::Static is removed from the middleware stack in production?


I am trying to understand how rails serves static files under /public, and if I get it correctly, the ActionDispatch::Static middleware is responsible for this.

However, I noticed that it's only available in development environment:

$ rake middleware

use Rack::Sendfile
use ActionDispatch::Static
use Rack::Lock
.
.

and in production:

$ RAILS_ENV=production rake middleware

use Rack::Sendfile
use Rack::Lock
.
.

How are static files served in production then? My guess is that this is handled by the web server itself (apache, puma...etc) to improve performace, is this correct?

And if that's the case, then why create a dedicated middleware for this task in development?

Thanks.


Solution

  • This is controlled by a setting in config/environments/production.rb:

    # Disable Rails's static asset server (Apache or nginx will already do this).
    config.serve_static_files = false
    

    The reason that this is not enabled in development, is because on development you don't need the extra functionality/overhead of nginx or apache. For example, you don't want your browser to get instructions to cache these files while developing.

    ActionDispatch::Static will just load these files from disk and send them to the browser, nothing fancy. All request to public will be handled by ActionDispatch::Static, all other requests are handled by your Rails application.