0
0
Nginxdevops~15 mins

Rewrite flags (last, break, redirect, permanent) in Nginx - Deep Dive

Choose your learning style9 modes available
Overview - Rewrite flags (last, break, redirect, permanent)
What is it?
Rewrite flags in nginx are special instructions that tell the server how to handle URL changes during request processing. They control whether nginx should stop processing further rules, redirect the user to a new URL, or continue with internal processing. These flags help manage how requests are routed and how URLs appear to users. Understanding them is key to customizing web server behavior.
Why it matters
Without rewrite flags, nginx wouldn't know when to stop rewriting URLs or when to send users to a different page. This could cause endless loops, incorrect page loads, or poor user experience. Proper use of these flags ensures efficient request handling, faster responses, and correct navigation, which are critical for website reliability and SEO.
Where it fits
Learners should first understand basic nginx configuration and URL rewriting concepts. After mastering rewrite flags, they can explore advanced nginx features like proxying, caching, and load balancing to build robust web servers.
Mental Model
Core Idea
Rewrite flags tell nginx exactly how to handle URL changes and when to stop or redirect during request processing.
Think of it like...
It's like giving a GPS with instructions: 'Turn here and stop,' 'Keep going,' or 'Take a detour to a new destination.' Each flag is a different instruction for the journey of a web request.
┌───────────────┐
│ Incoming URL  │
└──────┬────────┘
       │ rewrite rule applies
       ▼
┌───────────────┐
│ Rewrite Flags │
│ ┌───────────┐ │
│ │ last      │─┬─> Stop rewriting, process new URL
│ │ break     │─┬─> Stop rewriting, serve current request
│ │ redirect  │─┬─> Send client to new URL (302)
│ │ permanent │─┬─> Send client to new URL (301)
│ └───────────┘ │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is URL rewriting in nginx
🤔
Concept: Introduce the basic idea of changing URLs inside nginx before serving content.
URL rewriting means changing the requested URL to another one inside the server. For example, if a user asks for /old-page, nginx can rewrite it to /new-page before loading the content. This helps keep URLs clean or redirect old links.
Result
Requests can be internally changed to different URLs before content is served.
Understanding URL rewriting is the foundation for controlling how nginx handles web requests.
2
FoundationBasic syntax of rewrite directive
🤔
Concept: Learn how to write a simple rewrite rule with a pattern and replacement.
The rewrite directive looks like this: rewrite [flag]; Example: rewrite ^/old$ /new permanent; This means if the URL is exactly /old, rewrite it to /new and send a permanent redirect.
Result
nginx changes URLs based on patterns and optional flags.
Knowing the syntax lets you start customizing URL handling in nginx.
3
IntermediateUnderstanding the 'last' flag behavior
🤔Before reading on: do you think 'last' stops all rewriting or just the current rule? Commit to your answer.
Concept: The 'last' flag tells nginx to stop processing rewrite directives in the current location and restart processing with the new URL.
When you use 'last', nginx stops applying further rewrite rules in the current block and restarts the request processing with the rewritten URL. This can cause nginx to re-check location blocks and other rules for the new URL. Example: rewrite ^/old$ /new last; This means rewrite /old to /new and restart processing as if the client requested /new.
Result
nginx restarts processing with the new URL, applying all relevant rules again.
Understanding 'last' helps prevent unexpected loops or missed rules by restarting processing cleanly.
4
IntermediateDifference between 'break' and 'last' flags
🤔Before reading on: does 'break' restart processing like 'last', or does it stop differently? Commit to your answer.
Concept: 'break' stops rewrite processing immediately and continues with the current request without restarting.
Using 'break' means nginx stops applying rewrite rules right away and serves the request with the rewritten URL in the current location block. It does NOT restart processing or check other location blocks. Example: rewrite ^/old$ /new break; nginx serves /new without re-evaluating location or rewrite rules.
Result
nginx serves the rewritten URL immediately without restarting processing.
Knowing the difference prevents bugs where rules unexpectedly re-run or locations change.
5
IntermediateRedirect vs Permanent flags explained
🤔Before reading on: which flag sends a temporary redirect, and which sends a permanent one? Commit to your answer.
Concept: 'redirect' sends a temporary (302) redirect to the client; 'permanent' sends a permanent (301) redirect.
When you use 'redirect', nginx tells the browser to go to the new URL temporarily (HTTP 302). Browsers don't cache this. When you use 'permanent', nginx sends a permanent redirect (HTTP 301). Browsers cache this and update bookmarks. Example: rewrite ^/temp$ /new redirect; rewrite ^/old$ /new permanent;
Result
Clients are redirected to new URLs with appropriate HTTP status codes.
Choosing the right redirect type affects SEO and user experience.
6
AdvancedHow rewrite flags affect location matching
🤔Before reading on: does 'last' cause nginx to re-match location blocks? What about 'break'? Commit to your answer.
Concept: 'last' causes nginx to re-match location blocks with the new URL; 'break' does not.
When 'last' is used, nginx restarts processing and re-evaluates which location block matches the rewritten URL. This can change which configuration applies. With 'break', nginx stays in the current location block and serves the rewritten URL without re-matching. This difference is crucial when your server has multiple location blocks.
Result
'last' can change the handling location; 'break' keeps the current location.
Understanding this prevents misrouting and helps design complex nginx configurations.
7
ExpertUnexpected loops and performance with rewrite flags
🤔Before reading on: can misuse of 'last' cause infinite loops? How to avoid it? Commit to your answer.
Concept: Misusing 'last' can cause nginx to loop endlessly if rewrite rules keep triggering; careful rule design and conditions prevent this.
Because 'last' restarts processing, if a rewrite rule rewrites a URL back to a previous pattern, nginx can loop forever, causing errors or crashes. To avoid this, use conditions to prevent rewriting already rewritten URLs or use 'break' when no restart is needed. Example of loop: rewrite ^/foo$ /bar last; rewrite ^/bar$ /foo last; This causes infinite rewriting. Use flags and conditions carefully to prevent loops and optimize performance.
Result
Proper use avoids infinite loops and keeps nginx fast and stable.
Knowing this protects production servers from crashes and slowdowns.
Under the Hood
When nginx receives a request, it matches the URL against rewrite rules. Flags control whether nginx stops rewriting, restarts processing with the new URL, or sends a redirect response to the client. 'last' triggers a restart of location and rewrite evaluation with the new URL, 'break' stops rewriting but continues in the current location, and 'redirect'/'permanent' send HTTP redirect responses. Internally, nginx uses a state machine to track processing phases and flags influence transitions between these phases.
Why designed this way?
nginx was designed for high performance and flexibility. The flags provide precise control over request processing flow, allowing complex routing without heavy scripting. 'last' enables modular configuration by restarting processing, while 'break' offers a lightweight stop. Redirect flags separate internal rewriting from client-visible URL changes. This design balances speed, clarity, and power.
┌───────────────┐
│ Client Request│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Match Location│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Apply Rewrite │
│ Rules & Flags │
└──────┬────────┘
       │
       ├─> [last] ──> Restart location matching with new URL
       │
       ├─> [break] ──> Stop rewriting, continue current location
       │
       ├─> [redirect] ──> Send 302 redirect to client
       │
       └─> [permanent] ──> Send 301 redirect to client
       │
       ▼
┌───────────────┐
│ Serve Content │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does the 'break' flag cause nginx to re-match location blocks? Commit yes or no.
Common Belief:Many think 'break' restarts processing like 'last' and re-matches locations.
Tap to reveal reality
Reality:'break' stops rewrite processing immediately and continues in the current location without re-matching.
Why it matters:Misunderstanding this causes misconfigured servers where expected location changes never happen, leading to wrong content served.
Quick: Does 'permanent' redirect mean the URL is rewritten internally without client knowing? Commit yes or no.
Common Belief:Some believe 'permanent' just rewrites the URL internally like 'last'.
Tap to reveal reality
Reality:'permanent' sends a 301 HTTP redirect to the client, telling browsers to update the URL visibly.
Why it matters:Confusing internal rewrites with redirects can break SEO and user experience by hiding or exposing URLs incorrectly.
Quick: Can misuse of 'last' cause infinite loops? Commit yes or no.
Common Belief:Many assume rewrite flags never cause loops because nginx is smart enough to prevent them.
Tap to reveal reality
Reality:Improper rewrite rules with 'last' can cause infinite loops if URLs keep rewriting back and forth.
Why it matters:Infinite loops crash servers or cause slowdowns, making sites unavailable.
Quick: Does 'redirect' always mean permanent? Commit yes or no.
Common Belief:Some think 'redirect' means permanent redirect (301).
Tap to reveal reality
Reality:'redirect' means temporary redirect (302), while 'permanent' means 301.
Why it matters:Using the wrong redirect type affects caching, SEO rankings, and user bookmarks.
Expert Zone
1
Using 'last' inside nested location blocks can cause unexpected re-matching that changes the request handling path subtly.
2
Combining rewrite flags with try_files or proxy_pass directives requires careful ordering to avoid conflicts or unintended redirects.
3
Redirect flags affect client caching behavior; understanding HTTP status codes deeply helps optimize SEO and user experience.
When NOT to use
Avoid using rewrite flags for complex conditional logic; instead, use nginx map blocks or embedded scripting (like Lua) for better maintainability and performance. Also, do not use 'last' in infinite rewrite loops; use 'break' or conditional checks instead.
Production Patterns
In production, 'last' is often used to cleanly rewrite URLs and re-route requests, 'break' is used to rewrite URLs internally without changing location, and 'redirect'/'permanent' are used for SEO-friendly URL changes. Experts combine these with caching and proxying for scalable web services.
Connections
HTTP Status Codes
Rewrite flags 'redirect' and 'permanent' directly map to HTTP 302 and 301 status codes.
Understanding HTTP status codes clarifies how nginx communicates URL changes to browsers and search engines.
State Machines in Computing
nginx request processing with rewrite flags behaves like a state machine with transitions controlled by flags.
Viewing nginx as a state machine helps predict how flags affect request flow and avoid loops.
Traffic Routing in Road Networks
Rewrite flags are like traffic signs directing cars (requests) to stop, detour, or continue on the same road.
This analogy helps understand how small instructions can control complex routing efficiently.
Common Pitfalls
#1Creating infinite rewrite loops with 'last' flag.
Wrong approach:rewrite ^/foo$ /bar last; rewrite ^/bar$ /foo last;
Correct approach:rewrite ^/foo$ /bar last; # No rewrite back from /bar to /foo to avoid loop
Root cause:Misunderstanding that 'last' restarts processing and can cause repeated rewrites.
#2Using 'break' expecting location re-matching.
Wrong approach:rewrite ^/old$ /new break; # expecting nginx to re-match location for /new
Correct approach:rewrite ^/old$ /new last; # 'last' triggers location re-matching
Root cause:Confusing 'break' with 'last' behavior in nginx rewrite processing.
#3Using 'redirect' when permanent redirect is needed.
Wrong approach:rewrite ^/old$ /new redirect;
Correct approach:rewrite ^/old$ /new permanent;
Root cause:Not understanding difference between temporary (302) and permanent (301) redirects.
Key Takeaways
Rewrite flags control how nginx processes URL changes and when to stop or redirect requests.
'last' restarts request processing with the new URL, potentially changing location blocks.
'break' stops rewriting immediately and continues in the current location without restarting.
'redirect' and 'permanent' send temporary and permanent HTTP redirects to clients respectively.
Misusing rewrite flags can cause infinite loops or incorrect routing, so careful design is essential.