我的应用程序生成dynamic内容,我尝试使用浏览器caching来caching它们。 所以,如果我尝试添加到我的服务器块下面:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 365d; }
Nginx不再将请求传递给后端来生成资产,并且以http status code 404
相反,添加以下2个条件可以解决我的问题(从这个问题中得出):
location / { if ($upstream_http_content_type ~ "(image/jpeg)|(image/png)|(image/gif)|(image/svg+xml)|(text/css)|(text/javascript)|(application/javascript)") { expires 90d; } if ($sent_http_content_type ~ "(image/jpeg)|(image/png)|(image/gif)|(image/svg+xml)|(text/css)|(text/javascript)|(application/javascript)") { expires 90d; } try_files $uri @rewriteapp; } location @rewriteapp { rewrite ^(.*)$ /site.php/$1 last; } location ~ ^/(site|site_dev|admin|admin_dev)\.php(/|$) { # it's PHP that generates some of my assets fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS on; }
问题是, 我看不到在http响应头任何date,表明它的工作和图像将从浏览器caching服务90天 。
我错过了什么?
在您的PHP应用程序中生成HTTP响应时,您还应该查看有关响应标头的应用程序。 浏览器caching只是一个HTTP响应头问题。 所以如果你的应用程序提供了正确的头文件,你的web服务器将会为它们提供服
但是,您可以在Web服务器中覆盖此行为。 但是,在Web服务器级别执行此操作绝不是一个好主意。 这里只有URL和请求头来决定是否应该caching响应。 你的应用通常有更多的细节来做出更好的决定。
最好的方法是通过发送适当的caching头来修复你的PHP代码:
<?php ... header('Cache-Control: max-age='.90*24*3600);
对于替代方法,您可以(但不应该)在Nginxconfiguration中使用这个来覆盖Web应用程序的响应:
location ~ ^/(site|site_dev|admin|admin_dev)\.php(/|$) { # it's PHP that generates some of my assets fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS on; # hide response header sent by PHP fastcgi_hide_header Cache-Control; fastcgi_hide_header Expires; # set Cache-Control response for client expires 90d; }
更好的方法是在Web服务器级别caching。 在这里,您可以configurationexception,并能够对HTTP响应中的“Set-Cookie”标头等特殊情况做出反应。
顺便新来的客人也会获得快速交货的优势。 基于浏览器的caching不会帮助第一次访问者。
location ~ ^/(site|site_dev|admin|admin_dev)\.php(/|$) { # it's PHP that generates some of my assets fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS on; # activate caching (you must define a cache storage for phpfpm) fastcgi_cache phpfpm; # enable caching for 90 days for responses with HTTP status 200 fastcgi_cache_valid 200 90d; # allow headers from PHP to client fastcgi_pass_header Set-Cookie; fastcgi_pass_header Cookie; # ignore headers from PHP to client fastcgi_ignore_headers Cache-Control Expires Set-Cookie; # remove headers from PHP to client fastcgi_hide_header Cache-Control; fastcgi_hide_header Expires; # don't save in cache fastcgi_no_cache $cookie_PHPSESSID; # don't serve from cache fastcgi_cache_bypass $cookie_PHPSESSID; }
请注意,这只是基于标准设置的build议。 它可能会有所不同你的设置。