如何在 Heroku 上托管的 Sinatra 应用程序中设置 HTTP 响应(缓存)标头
我有一个相当简单的应用程序(只有一个 index.html
文件和一个 css 文件 - 它实际上只是一个静态页面)托管在 Heroku 上。
我使用 Sinatra 在 Heroku 上托管它。 “应用程序”本身相当简单:
require 'rubygems'
require 'sinatra'
get "/" do
File.read(File.join('public', 'index.html'))
end
问题是,如何设置静态资源的 HTTP 响应标头?特别是,我想设置 Expires
标头以进行缓存。
编辑:我希望将上述标头添加到静态资产中(即位于 /public
下的标头,如背景图像、图标等)
I have a fairly simple app (just one index.html
file and a css file - it really is just a static page) hosted on Heroku.
I use Sinatra to host it on Heroku. The 'app' itself is fairly simple:
require 'rubygems'
require 'sinatra'
get "/" do
File.read(File.join('public', 'index.html'))
end
The question is, how do I set the HTTP response header for the static assets? In particular, I wanted to set the Expires
header for caching purposes.
EDIT: I'm looking to add the said header to the static assets (ie, the one that resides under /public
, like background images, icons, etc)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了我不会仅仅为了提供静态文件而通过 Sinatra 堆栈这一事实之外,您还需要调用
缓存一分钟。
cache_control
是 Sinatra 附带的 帮助程序。否则,我建议您查看 http://www.sinatrarb.com/configuration.html< /a> 查看 Sinatra 的设置方式,这样您就不必处理提供静态文件的问题。
希望这有帮助。
编辑:我刚刚看到您明确要求
Expires
标头。我不确定,但这应该与 Cache-Control 完全相同。抱歉造成混乱Apart from the fact that I wouldn't get through the Sinatra stack just to serve static files, you'd call
to cache for a minute.
cache_control
is a helper that comes with Sinatra.Otherwise, I'd suggest you have a look at http://www.sinatrarb.com/configuration.html to see how Sinatra is set up so you don't have do deal with serving static files.
Hope this helps.
edit: I just saw you were explicitly asking for the
Expires
header. I'm not sure, but that should be fairly the same way asCache-Control
. Sorry for the confusion作为对 @awendt 答案的扩展,Sinatra 实际上可以处理静态文件,而无需显式定义路由并打印文件。
通过添加:
..您可以将
index.html
和stylesheet.css
添加到public/
文件夹。然后,当您访问 http://localhost:9292/stylesheet.css 时,您将获得静态文件。如果您想使用其他文件夹名称,而不是默认的
public/
,请尝试:如果我们想不那么明确,我们可以在无论如何,Sinatra 都会为我们启用
:static
:)来源: http://www.sinatrarb.com/configuration.html#__enabledisable_static_file_routes
As an expansion to @awendt's answer, Sinatra can actually handle static files with out needing to explicitly define the route and print the file.
By adding:
..you can add your
index.html
andstylesheet.css
to apublic/
folder. Then when you visithttp://localhost:9292/stylesheet.css
you'll be provided with the static file.If you want to use another folder name, instead of the default
public/
, then try:If we want to be less explicit we can just create the
public/
folder in the knowledge that Sinatra will enable:static
for us anyway :)Source: http://www.sinatrarb.com/configuration.html#__enabledisable_static_file_routes