How to Fix Nginx Rewrite Rule Error
In this tutorial, you'll learn about How to Fix Nginx Rewrite Rule Error. We cover key concepts, practical examples, and best practices.
Nginx rewrite rules cause infinite redirect loops or do not match as expected — the rewrite regex captures the wrong parts or the flag (last, break, redirect, permanent) is inappropriate for the use case.
The Problem
# Wrong: Causes redirect loop
rewrite ^/old-page$ /new-page permanent;
Without checking if the request is already for /new-page, this creates an infinite loop when subsequent rules process the new URI.
Step-by-Step Fix
Step 1: Use the correct rewrite syntax
# Simple redirect with redirect flag
rewrite ^/old-page$ /new-page redirect;
# Permanent redirect
rewrite ^/old-page$ /new-page permanent;
# Internal rewrite (no redirect to client)
rewrite ^/old-page$ /new-page last;
Step 2: Add condition to prevent loops
if ($request_uri !~ ^/new-page) {
rewrite ^/old-page$ /new-page permanent;
}
Step 3: Use return instead of rewrite for simple cases
# Better: Use return for simple redirects
location = /old-page {
return 301 /new-page;
}
# Regex-based redirect with return
location ~ ^/products/(.*)$ {
return 301 /shop/$1;
}
Step 4: Test rewrite rules
curl -I http://localhost/old-page
# Check Location header in response
Expected:
HTTP/1.1 301 Moved Permanently
Location: http://localhost/new-page
Step 5: Debug with logs
rewrite_log on;
error_log /var/log/nginx/rewrite.log notice;
Prevention Tips
- Prefer
returnoverrewritefor simple redirects - Use
breakflag to stop further rewrite processing - Always test rewrites with
curl -Ito check headers - Enable
rewrite_log onduring development
Common Mistakes with rewrite rule
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world NGINX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro