Step-by-Step Plan

1. Preparation in Cloudflare

This makes img.<domain> point to your same server but route through Cloudflare’s network.


2. Nginx Configuration

Create a vhost just for img.*, without PHP:

# /etc/nginx/conf.d/img.conf
map $host $tenant {
    ~^img\\.(?<dom>.+)$   $dom;
    default              "";
}

server {
    listen 443 ssl http2;
    server_name img.*;

    # Reuse your SSL certificate blocks

    root /var/www/app/public;

    # Do not execute PHP
    location ~ \\.php$ { return 404; }

    location / {
        try_files /local/$tenant$uri /local/$tenant$uri/ =404;

        add_header Cache-Control "public, max-age=31536000, immutable" always;
        add_header Access-Control-Allow-Origin "*" always;
    }
}

Reload Nginx:

nginx -t && systemctl reload nginx

3. Cloudflare Cache Rules

In Rules → Cache Rules, create one for img.*:

Optional under Speed → Optimization: enable Polish (WebP/AVIF) and Brotli.


4. Validation

  1. Open in your browser:

    https://img.<domain>/images/slug-ID.jpg