0

I recently switched over to nginx and am fairly new at it, so forgive me if this has been covered extensivly before.

What im trying to do is rewrite the user request based on tthe accept header sent out.

In paticular: if the accpet header is an image/gif or image/webp then serve the image, if not concat off the .gif of the url and serve that.

hears my apache configuration, but again im on nginx now and trying to learn how i could convert it over:

RewriteCond %{HTTP_ACCEPT} ^image/gif [NC] 
RewriteCond %{HTTP_ACCEPT} ^image/webp [NC] 
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com(.*)$ [NC]
RewriteRule ^i/(.*)\.gif http://example.com/i/$1 [R=302,L]

as you can see the above htaccess file works like a charm, but nginx is completly different it seems.

Ive done some reading and come up with this:

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

with the following inside the server block

location ~* ^/i/.+\.(gif)$ {
      root /storage-pool/example.com/public;
      add_header Vary Accept;
      try_files $uri$webp_suffix $uri =404;
}

Sadly, this doesnt work and I still dont know how to trouble shoot in nginx either.

Any information would be greatly appreciated, thanks.

user2360599
  • 83
  • 3
  • 3
  • 11

1 Answers1

0

From your location, the try_files will concat $uri with $webp_suffix which might not what you want, for example if you have a request to /i/test.gif with HTTP_ACCEPT header set to image/webp your location config above will try to find files at:

/storage-pool/example.com/public/i/test.gif.webp

You probably want something like this below instead:

location ~* ^(?P<basename>/i/.+)\.gif$ {
    root /storage-pool/example.com/public;
    add_header Vary Accept;
    try_files $basename$webp_suffix $uri =404;
}

This location will capture the image path without the .gif suffix and it will be available as variable named $basename

More information about named capture here: http://nginx.org/en/docs/http/server_names.html#regex_names

fudanchii
  • 192
  • 4