How to rewrite @2x retina image URLs with NGINX

Recently I noticed that one of our client websites was creating many 404 “not found” errors in our NGINX server logs. The errors were for “@2x.jpg” static files. I believe that the active Wordpress theme was coded to server @2x file URLs for retina and other HDPI screens, but the files are not automatically generated. Rather than dig into the theme’s template files and attempt some kind of patch, and since the website already looks great on high definition devices, I chose to look at adding a rule in the site’s NGINX .conf to stop these pesky 404s.

Normally a few Google searches would return a StackOverflow page with exactly the nginx rules required, but this time I could not dig up any pages where this problem had been addressed and fixed.

For Apache there was this post, where the .htaccess rules were perfectly coded. I even tried converting this ruleset to NGINX using an online converter, but the result was full of errors.

After some brief experimentation, I have a working NGINX ruleset that has solved my retina image 404 issue.

# rewrite retina image requests
location ~* ^(.*)\.(jpg|jpeg|png|gif)$ {
if ($request_filename ~ '@2x\.[a-z]+$') {
rewrite ^(.*)\@2x(.*)$ $1$2 last;