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);
if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
	$request = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
	if (!empty($request) && $request >= $latest ) {
		header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
		exit();
	}
}
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $latest) . ' GMT');
PHP

Now, on the page where the code is running, the server response will contain the Last-Modified header. You can check it in the last-modified.com 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');
PHP

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
96

Comments

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.
48
0
Serialize function, possible problems
The serialize () function returns a string representation of any value (array, object, etc.). Using serialize on an...
30
0
Examples of using cURL in PHP
cURL PHP is a library for receiving and transmitting data via protocols such as HTTP, FTP, HTTPS. The library is used...
316
0
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
60
0
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.
145
0
Working with PHP arrays - creating, filling, deleting
Basic examples of working with PHP arrays. Creation, filling, extraction and removal of values.
105
0