Mathieu Mahé
Mathieu Mahé

Reputation: 2746

Modify $uri in a nginx.conf

In my web application, I let the users upload their avatars and the application resize them in the background. That means that a user (or any user seeing a profile during the resize) will see a broken avatar since it has not been resized yet.

A way to fix this problem easily in my application would be to ask nginx to render the original image if the resized one doe not exist yet.

I was thinking about adding a line like try_files $uri $original_uri =404; in my nginx.conf but I don't know how to create the $original_uri variable.

$uri may looks like "users/42/thumb_avatar.jpg" and I need to transform it into "users/42/avatar.jpg".

So my question : Is there a way to apply a regex, or something like that, to modify a variable in the nginx.conf ?

Upvotes: 0

Views: 572

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15468

So in other words you need to strip a thumb_ prefix being present in the requested URI? Use a map block (should be placed at the http context outside the server block):

map $uri $original_uri {
    ~^(.*/)thumb_([^/]+)$  $1$2;
}
server {
    ...
}

Default value (if the regex pattern won't be matched) will be an empty string, which is OK for the try_files directive.

Upvotes: 1

Related Questions