0
0
NginxHow-ToBeginner · 3 min read

How to Use Rewrite in Nginx: Syntax and Examples

Use the rewrite directive in Nginx to change requested URLs by matching patterns and specifying new URLs. It works inside server or location blocks and supports regular expressions and flags like last or permanent to control behavior.
📐

Syntax

The rewrite directive has this basic syntax:

  • rewrite regex replacement [flag];

Here, regex is the pattern to match the original URL.

replacement is the new URL to use if the pattern matches.

flag controls what happens after rewriting, such as last to restart processing or permanent to send a 301 redirect.

nginx
rewrite regex replacement [flag];
💻

Example

This example rewrites URLs starting with /oldpath/ to /newpath/ and sends a permanent redirect to the client.

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        rewrite ^/oldpath/(.*)$ /newpath/$1 permanent;
    }
}
Output
When a user visits http://example.com/oldpath/page, they are redirected to http://example.com/newpath/page with a 301 status.
⚠️

Common Pitfalls

Common mistakes include:

  • Using rewrite outside of server or location blocks.
  • Forgetting to use anchors like ^ and $ in regex, causing unexpected matches.
  • Not specifying a flag, which defaults to last and may cause internal rewrites instead of redirects.
  • Confusing rewrite with return for simple redirects.

Example of wrong and right usage:

nginx
location / {
    # Wrong: missing regex anchors
    rewrite /oldpath/(.*) /newpath/$1 permanent;

    # Right: with anchors
    rewrite ^/oldpath/(.*)$ /newpath/$1 permanent;
}
📊

Quick Reference

FlagMeaning
lastStop processing current rewrite directives and search for a new location with the rewritten URL
breakStop processing rewrite directives in the current location
redirectSend a temporary 302 redirect to the client
permanentSend a permanent 301 redirect to the client

Key Takeaways

Use the rewrite directive inside server or location blocks to change URLs based on patterns.
Always include regex anchors (^ and $) to match URLs precisely.
Choose the correct flag to control whether the rewrite is internal or a redirect.
Test rewrites carefully to avoid redirect loops or unexpected behavior.
For simple redirects, consider using the return directive as a simpler alternative.