Regex Match Location in Nginx: How It Works and When to Use
regex match location is a way to match URLs using regular expressions inside location blocks. It lets you define flexible URL patterns for routing requests beyond simple prefixes. Regex locations start with ~ or ~* to indicate case-sensitive or case-insensitive matching.How It Works
Think of Nginx as a traffic controller for web requests. It decides where to send each request based on the URL. Normally, it matches URLs by checking if they start with a certain string, like a street name. But sometimes you want more control, like matching all streets that end with 'park' or contain numbers.
This is where regex match locations come in. They let you use regular expressions—special patterns that describe sets of strings—to match URLs. In Nginx, you write these patterns inside location blocks starting with ~ for case-sensitive or ~* for case-insensitive matching.
When a request comes in, Nginx checks these regex locations in order and picks the first one that matches the URL. This lets you handle complex URL patterns flexibly, like matching all URLs ending with '.php' or containing digits.
Example
server {
listen 80;
server_name example.com;
location ~ \.php$ {
root /var/www/html;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location / {
root /var/www/html;
index index.html;
}
}When to Use
Use regex match locations when you need to match URLs that can't be handled by simple prefix matching. For example:
- Routing all requests ending with a specific file extension like
.phpor.html. - Matching URLs with certain patterns, such as digits, dates, or specific words anywhere in the path.
- Handling case-insensitive URL matching with
~*.
They are useful in complex web applications where URL patterns vary and simple string matching is not enough.
Key Points
- Regex locations start with
~(case-sensitive) or~*(case-insensitive). - Nginx tests regex locations in order and uses the first match.
- Regex matching is more flexible but slower than prefix matching.
- Use regex only when prefix or exact matches are insufficient.
Key Takeaways
~ or ~* to match URLs with patterns.