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.serverblock: Defines the server configuration.locationblock: 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
rewritewithoutlastorpermanentflags, causing unexpected behavior. - Forgetting the semicolon
;at the end of thereturndirective. - Placing the redirect outside the correct
serverorlocationblock. - 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
| Directive | Purpose | Example |
|---|---|---|
| return 301 | Permanent redirect to new URL | return 301 https://example.com/new; |
| rewrite | Legacy redirect method | rewrite ^/old$ /new permanent; |
| location /path | Match URL path for redirect | location /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.