0
0
NginxHow-ToBeginner · 4 min read

How to Redirect URL in Nginx: Simple Guide with Examples

To redirect a URL in nginx, use the return or rewrite directive inside a server or location block. For example, return 301 https://newsite.com; sends a permanent redirect to the client.
📐

Syntax

The main directives to redirect URLs in nginx are return and rewrite. The return directive sends an HTTP status code and a new URL to redirect the client immediately. The rewrite directive changes the URL internally or externally based on patterns.

Common syntax:

  • return [status_code] [URL]; - sends a redirect with the given status code.
  • rewrite regex replacement [flag]; - rewrites URL matching regex to replacement, with optional flags like permanent for 301 redirect.
nginx
server {
    listen 80;
    server_name example.com;

    # Redirect using return
    location /oldpath {
        return 301 https://example.com/newpath;
    }

    # Redirect using rewrite
    location /oldpage {
        rewrite ^/oldpage$ /newpage permanent;
    }
}
💻

Example

This example shows how to redirect all requests from http://example.com/old to https://example.com/new using the return directive for a permanent redirect (HTTP 301).

nginx
server {
    listen 80;
    server_name example.com;

    location /old {
        return 301 https://example.com/new;
    }
}
Output
When a user visits http://example.com/old, the browser receives a 301 redirect and navigates to https://example.com/new.
⚠️

Common Pitfalls

Common mistakes when redirecting URLs in nginx include:

  • Using rewrite without the last or permanent flag, causing unexpected internal rewrites instead of redirects.
  • Placing redirect rules in the wrong server or location block, so they never trigger.
  • Forgetting to reload or restart nginx after changes, so redirects don't apply.
nginx
server {
    listen 80;
    server_name example.com;

    # Wrong: rewrite without flag (internal rewrite, no redirect)
    location /old {
        rewrite ^/old$ /new;
    }

    # Right: rewrite with permanent flag (301 redirect)
    location /old {
        rewrite ^/old$ /new permanent;
    }
}
📊

Quick Reference

DirectivePurposeExample
returnSend HTTP redirect with status codereturn 301 https://example.com/new;
rewriteRewrite URL with regex and optional redirectrewrite ^/old$ /new permanent;
listenDefine port to listen onlisten 80;
server_nameDefine domain nameserver_name example.com;
locationMatch URL path for ruleslocation /oldpath { ... }

Key Takeaways

Use the return directive for simple and clear URL redirects in nginx.
The rewrite directive requires flags like permanent to perform external redirects.
Always place redirect rules inside the correct server or location block.
Reload nginx after configuration changes to apply redirects.
Use HTTP status code 301 for permanent and 302 for temporary redirects.