如何在 Laravel 5 中添加浏览器缓存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36830867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add browser cache in Laravel 5?
提问by Yahya Uddin
I wish to add browser caching to my Laravel application.
我希望将浏览器缓存添加到我的 Laravel 应用程序中。
I have used Elixir versioning tool like so: https://laravel.com/docs/5.2/elixir#versioning-and-cache-busting
我使用过 Elixir 版本控制工具,如下所示:https: //laravel.com/docs/5.2/elixir#versioning-and-cache-busting
However, according to Google PageSpeed Insights, the files is still not caching and I instead got this message:
但是,根据 Google PageSpeed Insights 的说法,这些文件仍未缓存,而是收到了以下消息:
Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network.
在静态资源的 HTTP 标头中设置到期日期或最长期限会指示浏览器从本地磁盘而不是通过网络加载先前下载的资源。
I think this may be because I need to manually add cache headers?
我想这可能是因为我需要手动添加缓存头?
回答by Kevin
Yes you need to set Cache-Control
and Expires
in HTTP header for static resources, so that this Google PageSpeed message will not show up.
是的,您需要在静态资源的 HTTP 标头中设置Cache-Control
和Expires
,以便不会显示此 Google PageSpeed 消息。
Since you're already using Elixir versioning tool, you can safely set Expires of JS/CSS files to 1 week.
由于您已经在使用 Elixir 版本控制工具,您可以安全地将 JS/CSS 文件的过期时间设置为 1 周。
The way to do it depends on what web server you are using.
执行此操作的方法取决于您使用的 Web 服务器。
If you are using Apache
, you may put the following code in .htaccess
or the config file of your virtual website.
如果您正在使用Apache
,您可以将以下代码放入.htaccess
您的虚拟网站的配置文件中。
<FilesMatch "\.(js|css)$">
ExpiresActive On
ExpiresDefault "access plus 1 weeks"
</FilesMatch>
Be sure to enable the mod_expires
Apache module!
一定要启用mod_expires
Apache模块!
With the same syntax, you can set up cache rules for .html, .jpg, .png files and so on, to speed up page loading.
使用相同的语法,您可以为 .html、.jpg、.png 文件等设置缓存规则,以加快页面加载速度。
If you are using nginx, there are similar ways to solve this problem, you may follow this tutorial
如果你使用的是nginx,也有类似的方法可以解决这个问题,可以参考这个教程