Support Online
Skip to main content

Nginx Location Configuration: Exact Match, Regex and Proxy Settings

What Will You Learn in This Guide?

This guide explains how Nginx determines which location block will process incoming HTTP requests.
The aim is to prevent misdirection and create performant configurations.

Technical Summary

This content covers Nginx location directive logic and match priorities.
Regex usage, rootalias difference, and reverse proxy scenarios with proxy_pass are explained.


Location Operators and Their Meanings

Nginx uses different operators to determine match behavior:

OperatorMatch TypePriority
=Exact matchhighest
^~Prefix match (stops regex)High
~Regex (case sensitive)Medium
~*Regex (case insensitive)Medium
(none)Standard prefixlowest

Choosing the right operator is critical for both speed and safety.


Nginx Matching Algorithm

When Nginx receives a request it follows this order:

  1. Exact match (=) is checked
  2. Longest prefix is found
    • If ^~ exists the process ends here
  3. Regex blocks are executed in the order they are written in the file
  4. If the regex does not match, fall back to the prefix block

This mechanism provides predictable routing.


Difference Between root and alias

Using root

location /img/ {
root /var/www;
}
/img/logo.png → /var/www/img/logo.png

alias Usage


location /img/ {
alias /var/www/photos/;
}
/img/logo.png → /var/www/photos/logo.png

⚠️ The trailing / is mandatory when using aliases, otherwise a 404 will occur.

Reverse Proxy with proxy_pass


location /api/ {
proxy_pass http://127.0.0.1:8000/;
proxy_set_header Host $host;
}
  • This structure forwards API requests to the backend application. The trailing / prevents the /api path from being sent to the backend.

Applied Location Examples


# Tam eşleşme – sağlık kontrolü
location = /health {
return 200 "OK";
}

Static files – regex is blocked

location ^~ /static/ {
root /var/www/genixnode;
}

Backend routing

location /api/ {
proxy_pass http://127.0.0.1:8000/;
}
  • This structure is widely used in production environments.

Frequently Asked Questions

1. Why is the Regex order important? In Regex, the first match written in the file wins.

2. When to use ^~? When you don't want the prefix to be squashed by the regex.

3. How do I test the change without going live? Run sudo nginx -t.

4. The file exists but I'm getting a 404, why? It's usually a root-alias confusion or permission problem.


Result

A correct location hierarchy directly affects Nginx performance and security. You can prevent errors by testing your configurations and keeping them simple.

You can safely apply these settings in the GenixNode infrastructure.