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 likepermanentfor 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
rewritewithout thelastorpermanentflag, causing unexpected internal rewrites instead of redirects. - Placing redirect rules in the wrong
serverorlocationblock, so they never trigger. - Forgetting to reload or restart
nginxafter 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
| Directive | Purpose | Example |
|---|---|---|
| return | Send HTTP redirect with status code | return 301 https://example.com/new; |
| rewrite | Rewrite URL with regex and optional redirect | rewrite ^/old$ /new permanent; |
| listen | Define port to listen on | listen 80; |
| server_name | Define domain name | server_name example.com; |
| location | Match URL path for rules | location /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.