Permalink
Browse files

Make pages cacheable.

This change, which probably shouldn't be in Theme, but can't seem to easily go anywhere else under the current design, should make all pages cacheable.

First off it generates headers to make sure browsers actually try to cache the page. It may have been a server config on my side, but the max-age was always 0.

Then we generate an ETag based on the current state of the page, in a really hacky way.

If the ETag matches the HTTP If-None-Match header sent by the browser, we throw a 304 header and kill the connection.

If the ETag doesn't match and we have loaded posts to display, we check the first (usually most recent) post's modified timestamp and generate a Last-Modified header.

If the post's last modified timestamp is less than or equal to the HTTP If-Modified-Since header, we throw a 304 header and kill the connection.

Lastly, if we haven't already matched anything, we'll just throw an Expires header for 30 days in the future and continue processing.
  • Loading branch information...
1 parent 16476a1 commit 2dab8b584988d1d82f638d8cfcb5d74f13c6f3e0 @chrismeller committed Nov 19, 2011
Showing with 37 additions and 0 deletions.
  1. +37 −0 classes/theme.php
View
@@ -314,6 +314,43 @@ public function act_display( $paramarray = array( 'user_filters'=> array() ) )
}
}
}
+
+ // @todo probably need to make this private if the user is logged in so proxy's don't cache it?
+ header('Pragma: public', true);
+ header('Cache-Control: public, max-age=' . HabariDateTime::DAY * 30, true);
+
+ $etag = var_export( $this, true );
+ $etag = sha1( $etag );
+
+ header('ETag: ' . $etag, true);
+
+ if ( isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ) {
+ if ( $etag == $_SERVER['HTTP_IF_NONE_MATCH'] ) {
+ header( 'HTTP/1.1 304 Not Modified', true, 304);
+ header( 'X-Habari-Cache-Match: ETag');
+ die();
+ }
+ }
+
+ if ( isset( $post ) ) {
+ $last_modified = $post->modified->set_timezone( 'UTC' )->format( 'D, d M Y H:i:s e' );
+ $expires = HabariDateTime::date_create( '30 days' )->set_timezone( 'UTC' )->format( 'D, d M Y H:i:s e' );
+
+ header('Last-Modified: ' . $last_modified, true);
+
+ if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
+ $if_modified_since = HabariDateTime::date_create( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
+
+ if ( $post->modified <= $if_modified_since ) {
+ header( 'HTTP/1.1 304 Not Modified', true, 304 );
+ header( 'X-Habari-Cache-Match: Modified' );
+ die();
+ }
+ }
+
+ header('Expires: ' . $expires, true);
+ }
+
return $this->display_fallback( $fallback );
}

1 comment on commit 2dab8b5

Please sign in to comment.