Blocking image hotlinking on nginx running Ghost also breaks images on valid domain

I’m running Ghost on nginx 1.14.0 and Ubuntu 18.04. I am trying block image hotlinking by external sites.

I’ve added the recommended code from this post (starts with location ~* .(gif|png|jpe?g)$) to prevent image hotlinking.

Here is my site config file:

server {
listen 443 ssl http2;
listen (::):443 ssl http2;

root /var/www/; # Used for SSL verification (

ssl_certificate /etc/letsencrypt/live/;
ssl_certificate_key /etc/letsencrypt/live/;
include /etc/nginx/snippets/ssl-params.conf;

location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;

location ~* .(gif|png|jpe?g)$ {
    valid_referers none blocked *;
    if ($invalid_referer) {
        return 403;

location ~ /.well-known {
    allow all;

client_max_body_size 50m;}

The issue is when I add this code block and restart nginx, it works properly and blocks external requests returning a 403 Forbidden error. However, it also breaks local display of images despite the referer seemingly coming from the domain when I use the network inspector in Firefox to check the request.

I’ve tried adding different servers to the valid_referers line: localhost,, the ip of the server,*,*. Yet no matter how I configure the valid_referers line, images are still blocked when trying to load them from within the local site.

When I delete the entire hotlink blocking block, everything works fine locally and images are able to be hotlinked.

Any ideas? It’s been driving me crazy. Thanks in advance.