Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Using cookies and nginx web server configuration to conditionally serve high resolution images
<!doctype html>
<!--
Using cookies and nginx web server configuration to conditionally serve
high resolution images to <img> tags
-->
<html>
<head>
<!-- set device-pixel-ratio cookie using JavaScript -->
<script type="text/javascript" charset="utf-8">
if (!document.cookie.match(/\bdevice-pixel-ratio=/)) {
document.cookie = 'device-pixel-ratio='
+ (window.devicePixelRatio > 1 ? '2' : '1') + '; path=/';
}
</script>
<!-- set device-pixel-ratio cookie using CSS and server response -->
<style type="text/css">
@media only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
head {
background-image:url(/set-device-pixel-ratio/2);
}
}
</style>
</head>
<body>
<img src="/media/example.png" alt="image served in high res if available and appropriate">
</body>
</html>
# nginx example configuration
server {
# [...]
# Sets the device-pixel-ratio cookie
location ~ /set-device-pixel-ratio/(\d+)/? {
add_header Set-Cookie "device-pixel-ratio=$1;Path=/;Max-Age=31536000";
return 204; # nginx does not allow empty 200 responses
}
# Serves images in high resolution only if required
location ~ ^(/media/[^\.]+)(\.(?:jpg|png|gif))$ {
# Naming convention for high resolution images:
# <filename>@2x<extension>, e.g.:
# example@2x.png
set $hidpi_uri $1@2x$2;
if ($http_cookie !~ 'device-pixel-ratio=2') {
# If the device-pixel-ratio cookie is not set to 2, fall back to
# default behaviour, i.e. don't try to serve high resolution image
break;
}
# device-pixel-ratio cookie is set to 2
# Serve high resolution image if available,
# otherwise fall back to standard resolution
try_files $retina_uri $uri =404;
}
# [...]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment