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



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?

1 Answer 1


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 ) { ... }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .