Caching Objects, Passing Through and Rewrites

I’m trying to set up nginx to reverse proxy for our CDN to prevent
unauthorized access to raw video feeds. The idea is to restrict it to a
set
user-agent and referer, and if doesn’t match, to instead call the page
for
that video.

I would also like it to cache said video objects as well as any other
cachable objects, and to just pass other URLs through to origin.

Here’s my config so far:

upstream mainsite {
    server www.example.com;
}

upstream cdn {
    server example.cdnprovider.com;
}

server {
    listen *:80;

    # cachable objects, no restrictions
    location ~ (^/img|^/css|^/js|^/video/thumbnail|^/user/avatar) {
        proxy_pass       http://cdn$request_uri;
        proxy_set_header Host "content.example.com";
    }

    # raw video requests
    location ~ ^/video/raw {
        rewrite_log    on;
        valid_referers *.example.com example.com;

        # get the video id from the end of the string
        if ($uri ~* ^/video/raw/(.*)$) {
            set $vidid $1;
        }

        # The app is automatically passed
        if ($http_user_agent ~* Example-App) {
            proxy_pass http://cdn$request_uri;
        }

        # redirect requests for raw video to page for that video
        if ($invalid_referer) {
            rewrite ^(.*)$ /!$vidid break;  # example.com/!vidid
        }

        proxy_pass       http://mainsite$request_uri;
        proxy_set_header Host "www.example.com";
    }

    # everything else goes to origin, no caching
    location / {
        proxy_pass       http://mainsite$request_uri;
        proxy_set_header Host "www.example.com";
    }
}

The issue is that even without providing the correct user-agent or
referer,
I still get the raw video returned. Any help appreciated!

Posted at Nginx Forum: