How to Redirect to Another Domain in Nginx: Simple Guide
To redirect to another domain in
nginx, use the return 301 directive inside a server block with the target domain URL. This sends a permanent redirect telling browsers and search engines to go to the new domain.Syntax
The basic syntax to redirect to another domain in nginx uses the return directive with a status code and the new URL.
return 301 https://new-domain.com$request_uri;sends a permanent redirect (301) to the new domain, preserving the original request path.serverblock defines the domain or IP to listen on.
nginx
server {
listen 80;
server_name old-domain.com;
return 301 https://new-domain.com$request_uri;
}Example
This example shows how to redirect all traffic from old-domain.com to new-domain.com while keeping the path and query string intact.
nginx
server {
listen 80;
server_name old-domain.com www.old-domain.com;
return 301 https://new-domain.com$request_uri;
}Output
When a user visits http://old-domain.com/page?query=123, the browser is redirected to https://new-domain.com/page?query=123 with a 301 status code.
Common Pitfalls
Common mistakes when redirecting to another domain in nginx include:
- Using
rewritewithout proper flags, which can cause unexpected behavior. - Not preserving the original request URI, losing path and query parameters.
- Forgetting to specify the correct
server_name, so the redirect does not trigger. - Using
return 302(temporary redirect) when a permanent redirect (301) is intended.
nginx
server {
listen 80;
server_name old-domain.com;
# Wrong: rewrite without permanent flag and losing URI
rewrite ^ https://new-domain.com permanent;
# Right:
# return 301 https://new-domain.com$request_uri;
}Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| return 301 | Permanent redirect to new URL | return 301 https://new-domain.com$request_uri; |
| server_name | Defines domain to match | server_name old-domain.com www.old-domain.com; |
| listen | Port to listen on | listen 80; |
Key Takeaways
Use
return 301 https://new-domain.com$request_uri; inside the server block to redirect permanently.Preserve the original path and query by appending
$request_uri to the new domain URL.Ensure the
server_name matches the old domain to trigger the redirect.Avoid using
rewrite without flags for simple domain redirects.Test redirects to confirm they work and use the correct HTTP status code.