📜 ⬆️ ⬇️

Good advice: Avatars

Without ceasing to sing praises to nginx, I will introduce my decision to the public for a very simple display of avatars on projects.
The task is simple - to display the user's avatar, if he has one and display the default one, if the user has no avatar.
Suppose all avatars are physically stored in / img / avatar /, no matter what the names. The solution "in the forehead" will also be simple - to write to the database, whether the user has downloaded the avatar or not. But this will require contacting the database each time. Of course, you can use memkes and stuff, but there is a more elegant way out of the situation, in my opinion, to shift this task onto nginx’s shoulders. And nginx is very easy to handle:

error_page 404 =200 /img/avatar/default.gif;


Will explain. Suppose we know that the / avatar / directory stores an image that contains the user's id in the name. Type 1.jpg, 2.jpg etc. In the right place, we simply write the rule above, which tells nginx that with 404 answers here, return 200 answers and give the specified file.
In my versions of configs, it looks like this:

location ~* ^.+\.(jpg|jpeg|gif|png|js|txt|css|ico|zip|rar|xml|swf)$ {
if ( $request_uri ~* ^/img/avatar/.*$ ) {
error_page 404 =200 /img/avatar/default.gif;
expires -1;
add_header Cache-Control no-cache;
}
access_log off;
expires 7d;
}

Location to eliminate statics (everything else handles php), statics is not put in the log (access_log off;) and cached for 7 days (expires 7d;). But also, if the user applies for statics in / img / avatar /, try on our rule, at the same time we add anti-cache headers. That's all :)) Now, when the page is being generated, it does not soar us at all, whether the user uploaded an avatar or not, we simply link to it in src, and if there is no such file, nginx will give it back to default.
I apply the similar scheme on all the projects, never before there were no problems.

')

Source: https://habr.com/ru/post/50717/


All Articles