rails 4 生产环境中的资产未找到 404 错误

404 not found error for assets in rails 4 production enviroment

我是 java 环境中的 rails 新手。我对 rails 3 到 4 的资产管道几乎没有混淆。

目前我在rails 4.2.5 我在本地环境中创建了一个示例应用程序。 我从 app/assets/javascripts 内部创建了一个新的 js 并从视图中引用它,一切似乎在我的本地环境中都运行良好。

在此之后我想用生产环境测试它是如何工作的。这是我做的步骤。

  1. RAILS_ENV=production rake assets:clean assets:precompile [创建的所有文件public/assets]
  2. 以生产模式启动服务器rails server -e production
  3. 现在当我浏览页面时出现这个错误, "NetworkError: 404 Not Found - http://localhost:3000/assets/application-c5c431cb7c0a202f831a634922aaf1d536712002ae74334fb03ba4698b32b84c.js" 在 firebug.

当搜索了几个线程时,他们建议添加 config.assets.compile = true。但我不认为这就是解决方案,因为它会减慢应用程序的速度。

请帮忙。

By default Rails4 will return a 404 if an asset is not handled via an external proxy such as Nginx. - https://github.com/heroku/rails_serve_static_assets

我建议您查看 rails_12factor gem, which includes the rails_serve_static_assets gem,它将允许您的 Rails 应用提供静态资产(例如您的 .js 文件)。

编辑:

你可能不需要 gem(虽然我没试过):

config.serve_static_files configures Rails itself to serve static files. 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

在 Rails 5 中,此配置方法已重命名为 config.public_file_server.enabled,rails_serve_static_assets gem 根据版本处理正确的命名。