How to proxy Frontend images into Backend images?

2019-08-03 20:30发布

问题:

I'm facing a little problem to handle images. I have a Front server (site.com) and Back server (api.site.com), both linked by an NFS Storage for images. The original images are stored in the Back server. The Front server got only Nginx & NodeJs The back office got only Nginx & PHP

When I want to display an image: site.com/img/path-to-img-s250x250.jpg, it will search it in the NFS, if it exists, it's gonna be displayed, if not, then get the original image, resize it and save it in the NFS through our PHP script in the API server.

The rewriting rules you recommended me, will work only if i want to display images through the API (api.site.com/img/path-to-img-s250x250.jpg), but i'll need to display images trough the Front (site.com/img/path-to-img-s250x250.jpg), do you have any idea how I can achieve this?

# site.com/img/prods/10002/filename-w200h200-bgF00.12345.jpg
location ~ "^/img/(.*)/([a-z0-9-]+)-w([0-9]+)h([0-9]+)(-bg([0-9A-Fa-f]{3,6}))?\.[0-9]{5}\.(jpg|jpeg|png|gif|ico|webp)$" {
    try_files $uri /img/$1/$2-w$3h$4$5.$7 @redirect;
}

location @redirect {
    proxy_pass http://api.site.com;
    proxy_set_header X-ORIGIN http://api.site.com;
    proxy_set_header X-Requested-With XMLHttpRequest;
}

回答1:

Referring to your previous question (How can I check if file exists in nginx? otherwise run a rewrite rule) you need the final redirection to be external rather than internal.

You can achieve an external redirection by specifying a named location as the last parameter of the try_files statement.

For example:

location ~ "^/img/(.*/[a-z0-9]+-[0-9]+x[0-9]+)\.[0-9]{5}\.(jpg|jpeg|png|gif|ico)$" {
    try_files $uri /img/$1.$2 @resize;
}
location @resize {
    rewrite "^/img/(.*)/([a-z0-9]+)-([0-9]+)x([0-9]+)\.[0-9]{5}\.(jpg|jpeg|png|gif|ico)$" https://api.example.com/image?path=$1&file=$2&ext=$5&w=$3&h=$4 redirect;
}