Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
resize and crop images using nginx image_filter module with cache support
# My project directory is /home/rahit/www/mysite. I am storing cache file in my project folder under cache folder.
# You can use any of your prefered location in system. may be: /tmp/nginx
# I am naming keys_zone name my_cache. You can give it yours. We will need it later on in proxy_cache.
# Just make sure you put same zone name there
proxy_cache_path /home/rahit/www/mysite/cache levels=1:2 keys_zone=my_cache:10m max_size=1G;
# This is our media server, which will be used to resize and crop.
server {
listen 80;
server_name media.loc;
root /home/rahit/www/mysite;
# exaple url: /resize/<WIDTH>/<HEIGHT>/<IMAGE_PATH_FROM_ROOT>
# /resize/100/-/logo.jpg
# /resize/-/100/logo.jpg
location ~* ^/resize/([\d\-]+)/([\d\-]+)/(.+)$ {
alias /home/rahit/www/mysite/$3;
image_filter resize $1 $2;
image_filter_buffer 2M;
error_page 415 = /empty;
}
# exaple url: /crop/<WIDTH>/<HEIGHT>/<IMAGE_PATH_FROM_ROOT>
# /crop/100/-/logo.jpg
# /crop/-/100/logo.jpg
location ~* ^/crop/([\d\-]+)/([\d\-]+)/(.+)$ {
alias /home/rahit/www/mysite/$3;
image_filter crop $1 $2;
image_filter_buffer 2M;
error_page 415 = /empty;
}
location = /empty {
empty_gif;
}
}
# Here is our main server setting.
server {
listen 80;
root /home/rahit/www/mysite;
server_name mysite.loc www.mysite.loc;
# If we see an url which satisfy following regex we will pass this request to media server.
# Also we are going to cache the result we get from media server.
location ~* ^/(resize|crop)/ {
proxy_pass http://media.loc:80;
proxy_cache my_cache;
proxy_cache_key "$host$document_uri";
proxy_cache_valid 200 1d;
proxy_cache_valid any 1m;
proxy_cache_use_stale error timeout invalid_header updating;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment