简体   繁体   English

Apache:如何为 .js 和 .css 文件指定缓存?

[英]Apache: How to specify caching for .js and .css files?

I understand that during website development, caching can be disabled entirely at the start of any page using PHP using the directive我知道在网站开发期间,可以在使用 PHP 的任何页面开始时使用指令完全禁用缓存

if (getenv("DEVELOP"))
    header("Cache-Control: no-store");

But for production use, caching is desired for all files that do not often change.但是对于生产用途,所有不经常更改的文件都需要缓存。

My understanding is that Apache webservers cache HTML files (or the HTML produced by PHP files) by default, but not style or JavaScript files.我的理解是 Apache 网络服务器默认缓存 HTML 文件(或由 PHP 文件生成的 HTML),但不缓存样式或 JavaScript 文件。

I further understand that caching for non-HTML files can be specified either in the config file or in an .htaccess file using the directive "Header set Cache-Control".我进一步了解到,可以在配置文件或 .htaccess 文件中使用指令“Header set Cache-Control”指定对非 HTML 文件的缓存。 What are some typical ways to do this?有哪些典型的方法可以做到这一点?

Apache doesn't cache PHP, the code is executed each time. Apache 不缓存 PHP,每次都会执行代码。 However the code is compiled into zend vm bytecode provided PHP is loaded into apache as a module and the bytecode is stored until the underlying php file is changed.但是,如果 PHP 作为模块加载到 apache 中,并且字节码被存储,直到底层 php 文件发生更改,则代码会被编译为 zend vm 字节码。 The HTTP header is for the web browsers so they don't make repeated requests to your server. HTTP 标头用于 Web 浏览器,因此它们不会向您的服务器发出重复请求。

If you want to cache dynamic pages on your server using only apache and php you will have to do it yourself.如果您想仅使用 apache 和 php 在您的服务器上缓存动态页面,您必须自己做。 You can do it with php in numerous ways.您可以通过多种方式使用 php 做到这一点。 You can modify existing php files using php's output control funcitons and write the output to a file which would then be linked from your site.您可以使用 php 的输出控制函数修改现有的 php 文件,并将输出写入一个文件,然后该文件将从您的站点链接。 Then you will need to set up a cron, supervisor or systemd job to periodically run the php file(s).然后你需要设置一个 cron、supervisor 或 systemd 作业来定期运行 php 文件。

Alternatively some frameworks like laravel will do some caching for you if you configure it to.或者,如果您将其配置为某些框架,例如 laravel,它会为您做一些缓存。 A very popular solution nowadays is to combine apache with nginx for caching purposes.现在一个非常流行的解决方案是将 apache 与 nginx 结合用于缓存目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM