nginxreverse-proxyproxypass

Nginx proxy_pass to directory in if statement


what i want to do is reverse proxy b.com/c/d/1.jpg directory with a.com/1.jpg

location / {
    proxy_ssl_server_name on;
    if (!-e $request_filename) {
       # below will cause error: cannot have URI part in location given by regular expression, or inside named location, or inside \"if\" statement,
       # proxy_pass https://b.com/c/d; 
       proxy_pass https://b.com;
    }
}

can anyone help? how to do this on right way. THX.


Solution

  • Replace if (!-e $request_filename) with a try_files statement, and place the proxy_pass into a named location. Use rewrite...break to adjust the URI before it's passed upstream.

    For example:

    location / {
        try_files $uri $uri/ @proxy;
    }
    location @proxy {
        rewrite ^/(.*)$ /c/d/$1 break;
    
        proxy_ssl_server_name on;
        proxy_pass https://b.com;
    }