'Rails public folder items not available in production
I have a few items that are accessible just fine in development mode within the /public
directory of my app: favicon.ico
, robots.txt
.
I can view these in development at e.g. localhost:3000/favicon.ico
. However, when I push up to production, the assets are not visible at those paths. As a result, I don't have a favicon icon and google can't find my robots.txt file, among other things.
How can I fix this so that the /public
directory is accessible through relevant urls?
Solution 1:[1]
Rails 4.2+ (non-Heroku)
config/environments/production.rb
contains the line:
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
It means you can set RAILS_SERVE_STATIC_FILES
environment variable
(pass a command line when you starts your rails server, e.g.:)
RAILS_ENV=production RAILS_SERVE_STATIC_FILES=yes rails s -b 0.0.0.0 -p 3000
Heroku
For Heroku use the rails_12factor
gem for production in your Gemfile:
gem 'rails_12factor', group: :production
Rails 4.1 and below (the old way)
Add following line in your app/config/environments/production.rb
config.serve_static_assets = true
Here's what Rails Guides has to say
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.
Solution 2:[2]
Rails 5.1
Add following line in your app/config/environments/production.rb
config.public_file_server.enabled = true
Updated
config/environments/production.rb
contains the line:
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
It means you can pass RAILS_SERVE_STATIC_FILES
in a command line when you starts your rails server, e.g.:
RAILS_ENV=production RAILS_SERVE_STATIC_FILES=yes rails s -b 0.0.0.0 -p 3000
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jason FB |
Solution 2 |