2

I'm trying to forward all jpeg and png images to webp. It's a Laravel project. Most of images in /storage folder as a symlink in public folder. I followed guides and I know a bit regex but I couldn't find any clue what's wrong.

I have webp images in every folder.

path/to/image.jpg
path/to/image.jpg.webp

ngnix.conf file:

sendfile on;
tcp_nopush on;
tcp_nodelay on;

keepalive_timeout  65;

map $http_accept $webp_suffix {
    default "";
    "~*webp" ".webp";
}

Server config:

server{
    root /var/www/site/public;
    server_name example.com www.example.org;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    location ~*  \.(jpg|jpeg|png|webp|gif|ico|css|js)$ {
        expires 365d;
    }

    location ~* ^.+\.(png|jpe?g)$ {
        add_header Vary Accept;
        try_files $uri$webp_suffix $uri =404;
    }

    error_page 404 /index.php;

    if ($host = example.org) {
        return 301 https://www.example.org$request_uri;
    } # managed by Certbot 

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    }

    location ~ /\.ht {
        deny all;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }

    listen 443 ssl http2;
    listen [::]:443 ssl http2;
   
    ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}
server{
    if ($host = www.example.org) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.org) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    server_name example.org www.example.org;
    return 404; # managed by Certbot

}

I don't know what I am doing wrong. Any help will be appreciated thanks.

oguz463
  • 63
  • 6

1 Answers1

1

Regular expression location blocks are evaluated in order until a match is found. See this document for details.

You have two location expressions which match .png, .jpg and .jpeg. You need to remove these from the first expression for the second expression to succeed.

For example:

location ~* \.(gif|ico|css|js)$ {
    expires 365d;
}

location ~* \.(png|jpe?g)$ {
    expires 365d;
    add_header Vary Accept;
    try_files $uri$webp_suffix $uri =404;
}
Richard Smith
  • 45,711
  • 6
  • 82
  • 81