Skip to content

Instantly share code, notes, and snippets.

@polarlights
Forked from tmaiaroto/image-proxy.conf
Created December 18, 2015 11:08
Show Gist options
  • Save polarlights/dbb472fc19552e8a08da to your computer and use it in GitHub Desktop.
Save polarlights/dbb472fc19552e8a08da to your computer and use it in GitHub Desktop.
Nginx Image Filter Resize Proxy Service
# Feel free to change this path of course (and keys_zone value as well, but also change the usage of it below).
proxy_cache_path /var/www/cache/resized levels=1:2 keys_zone=resizedimages:10m max_size=1G;
# Gzip was on in another conf file of mine...You may need to uncomment the next line.
#gzip on;
gzip_disable msie6;
gzip_static on;
gzip_comp_level 4;
gzip_proxied any;
# Again, be careful that you aren't overwriting some other setting from another config's http {} section.
gzip_types image/jpeg image/jpg image/png image/gif;
server {
# Replace with your sub/domain.
server_name image.yoursite.com;
root /var/www/cache/store/img;
index index.html;
resolver 8.8.8.8 8.8.4.4;
# This requests the original file from itself and then resizes the image.
location ~ ^/resize/(\d+)x(\d+)/(.*) {
# Again replace with your sub/domain.
proxy_pass http://image.yoursite.com/$3;
proxy_cache resizedimages;
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;
image_filter resize $1 $2;
image_filter_jpeg_quality 90;
image_filter_buffer 20M;
image_filter_interlace on;
}
# Access denied.
location /resize {
return 403;
}
# RESIZED: http://image.yoursite.com/200x200/example.jpg
location ~ /(\d+x\d+/.*) {
try_files /$1 @img;
}
# ORIGINAL: http://image.yoursite.com/example.jpg
location / {
# If we don't find the file locally download it.
error_page 404 = @proxy;
}
# This saves the resized image locally.
location @img {
set $remote_uri $uri;
set $protocol "http";
if ($uri ~ "^/https?\:\/(.*)") {
set $remote_uri $1;
}
if ($uri ~ "^/https.*") {
set $protocol "https";
}
set $full_uri "${protocol}://${remote_uri}";
proxy_pass $full_uri;
proxy_store /var/www/cache/store/img/$full_uri;
}
# This gets the remote image and saves it locally.
location @proxy {
set $remote_uri $uri;
set $protocol "http";
if ($uri ~ "^/https?\:\/(.*)") {
set $remote_uri $1;
}
if ($uri ~ "^/https.*") {
set $protocol "https";
}
set $full_uri "${protocol}://${remote_uri}";
# i thought with merge_slashes off this would work... =(
#if ($uri ~ "^/(.*)") {
# set $full_uri $1;
#}
#set $full_uri $uri;
proxy_pass $full_uri;
proxy_connect_timeout 30s;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_store /var/www/cache/store/img$uri;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment