Mastering Nginx Rewrite: URL Redirection and Flag Options Explained
This guide explains how Nginx rewrite directives perform URL redirection without changing the browser address, covering syntax, placement rules, common use cases, detailed examples, and the meanings of flags like last, break, redirect, and permanent.
Rewrite in Nginx enables URL redirection without changing the address shown in the browser.
Purpose
It is commonly used for pseudo‑static URLs, e.g., converting /user/123 to /user.php?id=123.
Syntax
The basic directive is: rewrite regex replacement [flag]; where regex defines the matching rule, replacement is the target URL, and [flag] (optional) controls post‑rewrite behavior.
Rules
Rewrite can only be placed inside server{}, location{} or if{} blocks.
It operates on the part of the URL after the domain, excluding query parameters.
Examples
1. Redirect IE browsers to an /ie/ directory
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /ie/$1 break;
}2. Resize image requests
rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3 last;3. Domain jump
server {
listen 80;
server_name jump.test.com;
root /opt/www;
rewrite ^/ http://www.test.com/;
}4. Map a patterned directory to another rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2; 5. Convert a flat filename to a multi‑level path
rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;Flag meanings
last : equivalent to Apache’s [L], stops processing further rewrite rules in the current location and restarts the search with the new URI.
break : stops processing any further rewrite directives in the current server block.
redirect : returns a 302 temporary redirect.
permanent : returns a 301 permanent redirect.
Note that last does not terminate the matching of the rewritten URL, while break does.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
