Key Concepts and Examples of Nginx Regular Expressions
Nginx employs regular expressions to control URL behaviors effectively. Understanding Nginx’s handling of regex patterns is essential for optimizing web server configurations.
Basic Regular Expression Syntax:
^: Indicates the start of a string.$: Represents the end of the string.*: Matches zero or more occurrences of the preceding character (e.g.,12*matches1,12,122).+: Matches one or more occurrences of the preceding character (e.g.,12+matches12,122but not1).?: Matches zero or one occurrence of the preceding character (e.g.,12(34)?matches12or1234)..: Represents any single character except newlines.\: Escapes special characters, allowing literal matching.\d: Matches numeric values.{n}: Matches exactlynoccurrences.{n,}: Matchesnor more occurrences.{n,m}: Matches betweennandmoccurrences.[]: Defines a range or set of characters to match.[a-z]: Matches any lowercase letter.[a-zA-Z0-9]: Matches alphanumeric characters.()and|: Use parentheses for grouping and the pipe (|) for logical OR.
Location Matching in Nginx: Nginx relies on locations to route requests. Locations can be defined for exact matches, prefix matches, and regex-based matches. The priority rules define how matches are resolved:
- Exact matches (
location = / {...}). - Prefix matches (
location ^~ / {...}). - Case-sensitive regex matches (
location ~ {...}). - Case-insensitive regex matches (
location ~* {...}). - General prefix matches (
location / {...}).
Examples of Location Matching:
location = / { ... }: Matches only the root (/). Requests like/datadon't match.location / { ... }: Matches all requests because all URLs start with/.location ^~ /images/ { ... }: Matches paths starting with/images/, and skips further regex evaluation.location ~* .(gif|jpg|jpeg)$ { ... }: Matches URLs ending with image extensions but is overridden if a higher-priority match (^~ /images/) exists.
Using Rewrite in Nginx: The rewrite mechanism in Nginx modifeis or redirects incoming URLs using regex and flags. It can be used for purposes like rerouting requests or domain name redirection.
Rewrite Syntax and Flags:
- Format:
rewrite <regex> <replacement> [flag];<regex>: The matching pattern.<replacement>: The rewritten target.[flag]: Defines how the rewrite behaves, such as:last: Continues processing new location rules.break: Stops further processing.redirect: Sends a 302 temporary redirect.permanent: Sends a 301 permanent redirect.
Examples of Rewrite Rules:
- Redirect an old domain: Redirect requests from
www.old-domain.comtowww.new-domain.com.
server {
listen 80;
server_name www.old-domain.com;
location / {
if ($host = 'www.old-domain.com') {
rewrite ^/(.*)$ http://www.new-domain.com/$1 permanent;
}
root html;
}
}
- Restrict access by IP: Allow one specific IP to access the content, while others are shown a maintenance page.
server {
listen 80;
server_name www.example.com;
set $allowed_ip true;
if ($remote_addr = '192.168.1.1') { set $allowed_ip false; }
if ($allowed_ip = true) { rewrite ^ /maintenance.html break; }
location = /maintenance.html {
root /var/www/html;
}
location / {
index index.html;
}
}
- Path adjustment for certain domains: Redirect requests from
sub.example.comtowww.example.com/subpath.
server {
listen 80;
server_name sub.example.com;
location / {
rewrite ^ http://www.example.com/subpath permanent;
}
}
- Redirect based on specific pattterns: Forward requests matching a predefined regex.
server {
listen 80;
server_name www.example.com;
if ($request_uri ~ ^/old-(100|200)-(d+).html$) {
rewrite ^ /new-location permanent;
}
location / {
root html;
}
}
- Restrict directory-specific file types: Block access too PHP files in a folder, redirecting requests to the homepage:
server {
listen 80;
server_name www.example.com;
location ~ /uploads/.*\.php$ {
rewrite ^ / permanent;
}
location / {
index index.html;
}
}
Nginx offers powerful regex-based capabilities to meet diverse routing and content-serving needs effective, making it versatile for complex production environments.