Home > Back-end >  Redirect only if image/webp is present in accept header
Redirect only if image/webp is present in accept header

Time:11-19

So, I want to redirect all my images requests to another server, but I would like to check if image/webp is present on the accept header of the request before doing so, I was planning on doing that verification on the other server, but I think that it would be better to do it in nginx, is it possible to do that?

If the header was not present, I would just like to leave it as it is (serving the static image)

This is what I have rn:

location ~ \.(png|jpg|jpeg)$ {
    proxy_pass   ...;
}

CodePudding user response:

You can use the following:

map $http_accept $local {
    ~image/webp  '';
    default      $uri;
}
server {
    ...
    location ~ \.(png|jpe?g)$ {
        try_files $local @remote;
    }
    location @remote {
        proxy_pass ...
    }
}

However if the requested file is not found on the local server, request will be proxied to your remote server. If it isn't suitable for you, one of the possible ways is to use an evil if:

location ~ \.(png|jpg|jpeg)$ {
    if ($http_accept ~ image/webp) {
        proxy_pass ...
    }
}

This should work with the modern nginx versions, and if isn't evil in any situation, but this is exactly the one where I'd better avoid it. As an alternative you can use this one:

map $http_accept $locname {
    ~image/webp  remote;
    default      local;
}
server {
    ...
    location ~ \.(png|jpe?g)$ {
        try_files "" @$locname;
    }
    location @local {
        # serve the file locally
    }
    location @remote {
        proxy_pass ...
    }
}
  • Related