Nginx 302 redirect - resolve internally

Solution 1:

This is not ideal and it would be far better to have a clean workflow instead of doing this. But for curiosity, this could be informative to people that would wonder if it's possible.

Yes it is, using a combination of error_page, rewrite, map, proxy_intercept_errors and proxy_redirect directives and $upstream_http var pattern.

Keep in mind that it's going far off the path nginx is designed to be driven on.

map $upstream_http_location $redirect_uri {
    "~http://[^/]+/(?<location_uri>.*)$" "$location_uri";
}

upstream origin {
    server origin1.com;
}

server {

    listen 80;
    server_name nginx-front.com;

    proxy_set_header Host "origin1.com";
    proxy_redirect http://origin1.com/ /;

    location ~ ^/hls/(\w+)\.mp4\.m3u8$ {
        proxy_pass http://origin/m3ugen/segsrc/$1.mp4;
        proxy_intercept_errors on;
        error_page 301 302 = @handler;    
    }

    location @handler {
        rewrite ^ /$redirect_uri break;
        proxy_pass http://origin;
    }

}