Table of Contents

Nginx - Location block

About

A location block is a block that is located inside a server block and maps a a resource path to a destination path such as:

A server block may have several location block.

Example

server {
    location / {
        root /data/www;
    }

    location /images/ {
        root /data;
    }
    
    location ~* \.(gif|jpg|png)$ {
        expires 30d;
    }

    location ~ \.php$ {
        fastcgi_pass  localhost:9000;
        fastcgi_param SCRIPT_FILENAME
                      $document_root$fastcgi_script_name;
        include       fastcgi_params;
    }
}

Syntax

Syntax 1)

location [prefix] expression {
}

where:

An expression without prefix and the value /doc will match the directory /doc/ but also /docker

Regular expression

Regular expression in Nginx use the pcre syntax 2) with some twist such as you don’t have to escape the forward slash (/) in a URI as you do in a standard regex.

location ~* (?<begin>.*myapp)/(?<end>.+\.php)$ {
    #...
}

Processing

After the server has been found in the request processing, the second step is to find the location block.

The Location block processing follows the following algorithm;

Ref