Learning Center
Nginx

Nginx Location Directive Examples

22 Aug 2025
Adnene Mabrouk
Adnene Mabrouk

A useful tool for controlling the handling of several kinds of requests is the Nginx location directive. Specifying rules in the location directive lets you apply particular setups, divert requests to different areas of your application, or altogether refuse some requests. Using the Nginx location directive, you can maintain effective request management, which is important for improving web applications efficiency, security, and functionality. Learn how to set up Nginx here.

learning nginx directives

Nginx Location Directive is Simple to Remember

Nginx Location Directive Basic Syntax
Copy link

The Nginx location directive is defined in the configuration file nginx.conf. Below you can see its basic syntax:

location [modifier] uri { ... }
  • modifier: An optional parameter that defines the type of match (e.g., exact, prefix, regex).
  • uri: The URI to be matched.
  • Inside the curly braces, you can define various settings and instructions (e.g., proxy_pass, root, index).

Exact Match Example
Copy link

An exact match occurs when the requested URI exactly matches the specified string.

location = /exact-match {
    root /var/www/html;
    index index.html;
}

In this example, only requests to /exact-match will be processed by this location block.

An if statement can also be used to include a condition. Note that the standard if-else statement used in many programming languages has no direct equivalent in Nginx. However, conditional branching can be simulated by mixing numerous if statements with other directives to create comparable functionality.

location = /exact-match {
    root /var/www/html;
    index index.html;

    if ($http_user_agent ~* "Chrome") {
        add_header X-Browser "Chrome";
    }
}

In this case, if the user agent is identified as Chrome, the response will include an extra X-Browser header.

Prefix Match Example
Copy link

A prefix match is the most common type and matches any URI that starts with the specified string.

location /prefix {
    root /var/www/html;
    index index.html;

    if ($request_method = POST) {
        return 405; # Method Not Allowed
    }
}

This location block will handle any request beginning with /prefix—like /prefix/page1 or /prefix/page2. Should the request method be POST, Nginx results in a 405 Method Not Allowed status.

Regular Expression Match Example
Copy link

Regular expressions are helpful in more challenging matching situations. Wildcards are characters that can fit any character or group of characters in the regular expression match in Nginx. In Nginx regular expressions, common wildcards are:

  • .: Matches any single character.
  • .*: Matches any sequence of characters (including no characters).
  • ^: Matches the beginning of a string.
  • $: Matches the end of a string.
location ~* \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi_params;

    if ($request_uri ~* "/admin") {
        return 403; # Forbidden
    }

    if ($request_uri !~* "/admin") {
        add_header X-Admin "Not Admin";
    }
}

In this example:

  • The ~* modifier indicates a case-insensitive regular expression match.
  • The pattern \.php$ matches any URI ending with .php (e.g., index.php, test.PHP).
  • If the requested URI contains /admin, Nginx returns a 403 Forbidden status.
  • If the requested URI does not contain /admin, an X-Admin header is added indicating "Not Admin".

Case Insensitive Match Example
Copy link

You can use regular expression with the ~* modifier for case-insensitive matching.

location ~* \.jpg$ {
    root /var/www/images;

    if ($http_referer !~* "^https?://(www\.)?example\.com") {
        return 403; # Forbidden
    }
}

This matches any URI ending with .jpg, .JPG, .Jpg, etc., and only serves the image files if the referer is from example.com. Otherwise, it returns a 403 Forbidden status.

Priority and Order
Copy link

The priority and order of location blocks are critical for correctly processing requests. Nginx follows these rules:

  1. Exact match (=): These have the highest priority.
  2. Regular expressions (~ or ~*): Evaluated in the order they are defined in the configuration file.
  3. Prefix matches without modifier: These have the lowest priority, but among them, the longest prefix has the highest priority.

Example

location = /exact {
    # highest priority
}

location ~* \.jpg$ {
    # lower priority than exact match
}

location / {
    # lowest priority
}

Nesting Location Blocks
Copy link

Nginx allows nesting of location blocks within other location blocks for more granular control.

location /nested {
    location /nested/subnested {
        root /var/www/html;
    }
    root /var/www/html;
}

In this example, requests to /nested/subnested will be processed by the inner location block, while /nested (but not /nested/subnested) will be processed by the outer location block.

Real Web Server Example
Copy link

Let's consider a practical example of configuring a local web server with multiple location blocks.

server {
    listen 80;
    server_name localhost;

    # Root location block
    location / {
        root /var/www/html;
        index index.html;
    }

    # Exact match for a specific page
    location = /about {
        root /var/www/html;
        index about.html;
    }

    # Prefix match for an API endpoint
    location /api {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Regular expression match for PHP files
    location ~ \.php$ {
        root /var/www/html;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    # Case insensitive match for image files
    location ~* \.(jpg|jpeg|png|gif|ico)$ {
        root /var/www/images;
    }

    # Nested location blocks for admin section
    location /admin {
        root /var/www/admin;
        index index.html;

        location /admin/stats {
            proxy_pass http://localhost:8080/stats;
        }
    }
}

In this configuration:

  • The root location serves static files from /var/www/html.
  • Requests to /about are served by the exact match block pointing to about.html.
  • The /api prefix is proxied to a backend service running on port 3000.
  • PHP files are processed by a FastCGI server.
  • Image files are served from /var/www/images.
  • Nested location blocks are used to handle /admin and /admin/stats with different settings.

Nginx main configuration file contains the core configuration directives for the Nginx server. Nginx config file location is usually /etc/nginx/nginx.conf.

You have to reload the service after making changes to the Nginx configuration in order for the changes to take effect. Running the following will accomplish this without deleting any active connections:

sudo systemctl reload nginx

Testing and Debugging Location Blocks
Copy link

It's important to verify that each location block works as intended before deploying or relying on a NGINX configuration. We will provide simple ways to test your setup, catch misconfigurations early, and troubleshoot common issues using built-in tools like curl and log files.

Check configuration syntax before applying changes this way:

sudo nginx -t

Next, reload NGINX to apply changes without dropping active connections:

sudo systemctl reload nginx

Test location behavior with curl and send requests to check if the correct location block responds:

curl -I http://localhost/about
curl -X POST http://localhost/prefix/form
curl -H "User-Agent: Chrome" http://localhost/exact-match

Check for status codes, headers, and content.

View request handling and errors in real-time:

tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

Let's write down a location block troubleshooting checklist.

  • Ran nginx -t? Make sure the config syntax is valid.
  • Reloaded NGINX? Remember to reload after changes.
  • Does the request match exactly? Confirm the requested URI matches the block as expected (consider trailing slashes).
  • Is block priority correct? Check if a higher-priority block is taking over.
  • Does the root path exist? Ensure root or alias points to a valid directory/file.
  • Used curl or browser tools? Inspect request/response details to trace behavior.
  • Have you checked the logs? Look for access and error log entries related to your request.
  • Have you tried isolating the block? Temporarily comment out other blocks to confirm which one is handling the request.

Sensitive Locations Access Restriction
Copy link

To keep things safe, limiting who can access private routes like /admin, /config, or internal tools is smart. The allow and deny directives in NGINX let you control entry based on an IP address.

location /admin {
    allow 192.168.1.100;
    deny all;
    root /var/www/admin;
    index index.html;
}

The /admin path can only be reached by the client at 192.168.1.100 in this case. A 403 Forbidden answer will be sent to any other IP that tries to reach it. You can also allow multiple addresses or ranges and deny the rest. This method is simple and effective for securing access without relying on authentication or external tools.

Understanding root vs alias in Location Blocks
Copy link

Depending on how your location block is set up, you need to use the right directive when sending static files. This could be root or alias. Misusing these can cause NGINX to fail to locate files correctly.

Here’s a quick comparison:

Directive

Behavior

Example URI

Config Path

Resulting File Path

root

Appends URI after match

/static/css/style.css

location /static/ { root /var/www; }

/var/www/static/css/style.css

alias

Replaces matched URI prefix

/static/css/style.css

location /static/ { alias /var/www/assets/; }

/var/www/assets/css/style.css

Example using alias, where the request to /files/manual.pdf will serve the file at /data/downloads/manual.pdf:

location /files/ {
    alias /data/downloads/;
}

Note: When you use alias, always add a backslash (/) to the end of the path if your address ends in /. This will keep the paths from not matching. 

Nginx directives working scheme

Nginx Directives Working Scheme

Conclusion
Copy link

A solid understanding of the location directive is essential to refine the management of the request handling. This includes an understanding of different matches — exact (=), prefix (/), and regular expression-based (~, ~*) — and how Nginx prioritizes them. Using them right can significantly impact performance and behavior of your website.

You can also nest location blocks to apply more targeted rules within broader contexts, giving you tight control over how different URLs are processed. Mastering these patterns helps build a configuration that's both clean and highly efficient.

Check our latest and affordable VPS Hosting configurations from Hostman. And don't forget to check our Wordpress hosting!