Home > Blockchain >  How to combine 2 rewrite rule to load webp file in Nginx?
How to combine 2 rewrite rule to load webp file in Nginx?

Time:02-17

I am running a WordPress website in the Nginx.

And to load the Webp file, the following Rewight rule is used.

It works fine when there is only one code in it.

    location ~ /wp-content/(?<path>. )\.(?<ext>jpe?g|png|gif)$ {
    if ($http_accept !~* "image/webp") {
      break;
    }
    add_header Vary Accept;
    expires 365d;
    try_files /wp-content/uploads-webpc/$path.$ext.webp $uri =404;
  }


    location ~ /wp-content/(?<path>. )\.(?<ext>jpe?g|png|gif)$ {
    if ($http_accept !~* "image/webp") {
      break;
    }
    add_header Vary Accept;
    expires 365d;
    try_files /wp-content/$path.$ext.webp $uri =404;
  }

But my webp file is split in two paths.

/wp-content/$path.$ext.webp
/wp-content/uploads-webpc/$path.$ext.webp

If i paste these both code into nginx's site.conf at the same time, it won't work.

I'm wondering how can I combine these two into one.

Thank you.

CodePudding user response:

I'm not sure what were you trying to achieve with that if ($http_accept !~* "image/webp") { break; } part. If you think it is a way to exit the current location and search the next one, you are wrong. The break directive will stop processing of any further directives from the ngx_http_rewrite_module (but you haven't had any more of them, so it simply does nothing) and your configuration will serve the request with the WEBP file no matter if the client browser support it or not. The classic way to serve the WEBP file in case the Accept HTTP header contains the image/webp string is to use the following map block:

map $http_accept $suffix {
    ~image/webp    .webp;
    default        '';
}
server {
    ...
    location ~ \.(jpe?g|png|gif)$ {
        add_header Vary Accept;
        try_files $uri$suffix $uri =404;
    }
    ...
}

Depending on what of those two files you want to check first, you should use

try_files /wp-content/$path.$ext$suffix /wp-content/uploads-webpc/$path.$ext$suffix $uri =404

or

try_files /wp-content/uploads-webpc/$path.$ext$suffix /wp-content/$path.$ext$suffix $uri =404

and only one location block from your question.

  • Related