0
0
NginxHow-ToBeginner · 3 min read

How to Redirect 301 in Nginx: Simple Guide

To create a 301 redirect in nginx, use the return 301 directive inside a server or location block. This tells Nginx to permanently redirect requests to a new URL.
📐

Syntax

The basic syntax for a 301 redirect in Nginx uses the return 301 directive followed by the new URL. It is placed inside a server or location block.

  • return 301 <new_url>;: Sends a permanent redirect status with the new URL.
  • server block: Defines the server configuration.
  • location block: Defines specific URL patterns to match.
nginx
server {
    listen 80;
    server_name example.com;

    location /old-path {
        return 301 https://example.com/new-path;
    }
}
💻

Example

This example shows how to redirect all requests from http://example.com/old-page to https://example.com/new-page permanently using a 301 redirect.

nginx
server {
    listen 80;
    server_name example.com;

    location = /old-page {
        return 301 https://example.com/new-page;
    }
}
Output
When a user visits http://example.com/old-page, the browser receives a 301 Moved Permanently response and is redirected to https://example.com/new-page.
⚠️

Common Pitfalls

Common mistakes when setting up 301 redirects in Nginx include:

  • Using rewrite without last or permanent flags, causing unexpected behavior.
  • Forgetting the semicolon ; at the end of the return directive.
  • Placing the redirect outside the correct server or location block.
  • Redirect loops caused by redirecting to the same URL.

Correct usage example:

nginx
location /old {
    # Wrong: missing semicolon
    # return 301 https://example.com/new;

    # Right:
    return 301 https://example.com/new;
}
📊

Quick Reference

DirectivePurposeExample
return 301 ;Permanent redirect to new URLreturn 301 https://example.com/new;
rewrite permanent;Legacy redirect methodrewrite ^/old$ /new permanent;
location /pathMatch URL path for redirectlocation /old-path { return 301 https://example.com/new; }

Key Takeaways

Use return 301 <new_url>; inside a server or location block for permanent redirects.
Always include the semicolon ; after the return directive to avoid syntax errors.
Place redirects carefully to avoid loops and ensure they match the correct URL patterns.
Prefer return 301 over rewrite for simple permanent redirects.
Test redirects with a browser or curl to confirm the 301 status and correct target URL.