How to set up Last-Modified

How to set up Last-Modified

The Last-Modified header helps to optimize the loading of web pages and facilitate the work of search robots (the robot will be able to get information about whether the page of the site has been updated since the last indexing), the date will be shown in the search results next to the pages of your site.

The algorithm is as follows: the search robot "asks" the server if the page has changed since a certain date. If the page has changed, the server returns the page as usual; if there have been no changes, only the header "304 Not Modified" is returned.

An example for a module of articles or news, it is assumed that the database stores the creation and modification dates of the article in the UnixTime format. The code is placed before the content is output to the browser.

// We collect the dates of creation and modification of the article.
$dates[] = 1450462745;
$dates[] = 1482085145;

$latest = max($dates);
	$request = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
	if (!empty($request) && $request >= $latest ) {
		header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $latest) . ' GMT');

Now, on the page where the code is running, the server response will contain the Last-Modified header. You can check it in the service or in the browser code inspector:

If it doesn't work

There is no header in the server response, but for example Last-Modified-x is:

header('Last-Modified-x: ' . gmdate('D, d M Y H:i:s') . ' GMT');

The reason is in nginx and the ngx_http_ssi_module - it removes the Last-Modified header sent from PHP, you need to disable the SSI module in the nginx config.

location / {
	ssi off;
18.12.2016, updated 26.03.2021


to add a comment.

Other publications

Checking data with regular expressions
A collection of regular expressions with examples in PHP for validating data from form fields.
Serialize function, possible problems
The serialize () function returns a string representation of any value (array, object, etc.). Using serialize on an...
How to find out if a request came via AJAX
To distinguish between direct and AJAX requests, simply check the value of the $ _SERVER global variable
Session lifetime in PHP
By default, in php, the session lifetime is only 24 minutes, and cookies are saved until the browser is closed, such parameters are set on many hosting services.
Writing and reading files in PHP
Examples of saving and reading text data and arrays to files.
Disable PHP caching
Sometimes on hostings PHP opcache caching is enabled by default. Edits were made in the code, but on the site everything is displayed as before...