Skip to content

How to Use Nginx Rewrite Rules

DodaTech Updated 2026-06-24 2 min read

Rewrite rules in Nginx allow URL transformation for SEO, migration, and application routing. Using return is more efficient than rewrite for simple cases. This guide walks through the specific troubleshooting steps to diagnose and resolve rewrite issues.

Before You Begin

Before you begin, be sure to have the following in place:

  • A Linux server with the relevant software installed
  • Access to the command line interface
  • Appropriate permissions (root or sudo)

Quick Fix

Wrong

rewrite ^/old$ /new permanent;

Wrong: Using rewrite for simple redirects

location /old {\n    return 301 /new;\n}

Right: Using return for simple redirects (more efficient)

Output

Redirect: /old → /new (301 permanent)\nNginx rewrite module optimized

Prevention

To avoid future issues, follow these best practices:

  • Use return instead of rewrite for simple redirects -- it is faster
  • Use rewrite for complex URL transformations (regex capture groups)
  • Use last flag to stop rewriting and search for new location
  • Use break flag to stop rewriting but keep current location
  • Use permanent (301) for permanent redirects and redirect (302) for temporary

DodaTech Tools

For further assistance with any of the above issues, consider using DodaTech consulting services or DodaTech tutorials for more in-depth guidance.

Common Mistakes with rewrite

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

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

When should I use rewrite instead of return?|||Use return for simple path-to-path redirects. Use rewrite when you need regex substitution: rewrite ^/article/(\d+)$ /post?id=$1 last;.
What is the difference between the last and break flags? last stops current rewrite and Nginx searches for a new location matching the rewritten URI. break stops rewrite processing but keeps the current location.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro