Nginx Part of Uri in Variable

nginxrewrite

I'd like to put a part of a URI in nginx into a Variable. Currently I've this rule.

if ( !-e /tmp/access_22092012_$cookie_PHPSESSID.tmp ) {
        rewrite /folder1/folder2/(.*) /folder1/folder1.php?file=$1 last;
}

The requests are like

http://my.domain/folder1/folder2/22092012/index.html

http://my.domain/folder1/folder2/22092012/files/x.sfw

Where 22092012 can be have also other numbers.

I'd like to extract the Part 22092012 from the URL put it in a variable, what then goes in the file exists condition above:

if ( !-e /tmp/access_$urlpart_$cookie_PHPSESSID.tmp ) {
        rewrite /folder1/folder2/(.*) /folder1/folder1.php?file=$1 last;
}

Why I need this: I make a login protection to protect files with a session login. My Application writes the tmp Files, so if in a folder are 100 files, the script doesn't need to verify for each file if it has permission for it and don't need to run for each file a php worker.

Is this possible?

Best Answer

Yes -- you can use regular expression with 'captures' in location, and reference them in location block, like so:

location ~ /folder1/folder2/(.*)/ {
    if ( !-e /tmp/access_$1_$cookie_PHPSESSID.tmp ) { ... }
}