Nginx - Location block


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.


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
        include       fastcgi_params;


Ref doc

location [prefix] expression {


  • prefix is optional may be:
    • = matches exactly the expression
    • ~ indicates a regular expression match
    • ~* the asterisk after the tilde makes the match case insensitive.
  • expression is an expression that is matched only against the URL path part (and not the query part because it can can have many form for the same data. ie user=john&page=1 is equivalent to page=1&user=john)

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

Regular expression

Regular expression in Nginx are the pcre syntax

  • Name group capture is supported. Below is example of two groups with the name begin and end respectively.
location ~* (?<begin>.*myapp)/(?<end>.+\.php)$ {



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;

  • nginx first searches for the most specific prefix location given by literal strings regardless of the listed order.
  • then:
    • nginx checks locations given by regular expression in the order listed in the configuration file.
    • The first matching regular expression is chosen
    • If no regular expression matches a request, then nginx uses the most specific prefix location found earlier.


Powered by ComboStrap