问题原文
原帖链接 · skibulk · CC BY-SA 4.0
I'm trying to reduce my server load by providing 304 Not Modified responses for content where appropriate. CloudFlare is my middle man, so they should be sending If-Modified-Since headers whenever a cached page has expired, right?
I'm receiving these responses, client-side:
CF-Cache-Status: MISSon first page loadCF-Cache-Status: Hiton page reloads for 20 secondsCF-Cache-Status: EXPIREDon page reload after 20 seconds
The expired request is forwarded to my server, but doesn't include an If-Modified-Since header. How can I get this to work?
<?php
$now = time();
header( "ETag: W/\"$now\"" );
header( 'Expires: '.gmdate('D, d M Y H:i:s \G\M\T', $now + 20) );
header( 'Last-Modified: '.time() );
header( 'Cache-Control: public, max-age=20' );
print('<pre>');
print_r($_SERVER);
print('</pre>');
已采纳解答
原帖链接 · skibulk · CC BY-SA 4.0
First, make sure you've configured Cloudflare with Cache Level: Cache Everything and Origin Cache Control: On, whether in the global settings or as a page rule.
Additionally, you must not set a cookie in the Origin response, max-age=0, or a past expires date. Doing so will prevent Cloudflare from caching the page.
Note that some hosts (usually free or shared hosts) will remove any If-Modified-Since and ETag headers. This is supposedly done because these headers can cause extra requests on the server. If you run the following script twice in a row (6 seconds apart), you should see the If-Modified-Since header printed on the page. Otherwise, your Last-Modified header was removed before the page was sent to Cloudflare. This is done outside of the PHP script, whether in the Apache configuration or other server settings. Note: as of January 2020, 000webhost removes the Last-Modified header and Freehostia does not.
/*if( isset( $_SERVER[ 'HTTP_IF_MODIFIED_SINCE' ] ) )
{
header( "HTTP/1.1 304 Not Modified" );
exit();
}*/
header( "Cache-Control: max-age=5");
header( "Last-Modified: " . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
echo "<h1>Request Headers received by the server (from Cloudflare):</h1>\r\n<pre>";
print_r( getallheaders() );
echo "</pre>"
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
