How to Redirect www to Non-www in Nginx: Simple Guide
To redirect
www to non-www in Nginx, create a server block for the www domain that uses a return 301 directive pointing to the non-www URL. This sends a permanent redirect so visitors and search engines go to the preferred domain.Syntax
The basic syntax to redirect www to non-www in Nginx involves creating a server block for the www domain and using the return 301 directive to send a permanent redirect to the non-www domain.
server_name www.example.com;specifies the domain to redirect from.return 301 https://example.com$request_uri;sends a permanent redirect to thenon-wwwdomain, preserving the path and query.
nginx
server {
listen 80;
server_name www.example.com;
return 301 https://example.com$request_uri;
}Example
This example shows a complete Nginx configuration that redirects all www.example.com requests to example.com using a permanent redirect. It preserves the full URL path and query string.
nginx
server {
listen 80;
server_name www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 80;
server_name example.com;
root /var/www/example.com/html;
index index.html;
}Output
When a user visits http://www.example.com/page?query=1, the browser is redirected to https://example.com/page?query=1 with a 301 status code.
Common Pitfalls
Common mistakes when redirecting www to non-www include:
- Not preserving the URI path and query string, causing users to lose their requested page.
- Using
rewriteinstead ofreturn, which is less efficient for simple redirects. - Forgetting to configure SSL redirects if HTTPS is used, leading to mixed content or insecure warnings.
nginx
server {
listen 80;
server_name www.example.com;
# Wrong: rewrite without permanent flag and missing URI
rewrite ^ https://example.com$request_uri permanent;
}
# Correct way:
server {
listen 80;
server_name www.example.com;
return 301 https://example.com$request_uri;
}Quick Reference
Remember these tips for www to non-www redirection in Nginx:
- Use
return 301for simple, permanent redirects. - Always preserve
$request_urito keep the full path and query. - Configure both HTTP and HTTPS server blocks if your site uses SSL.
- Test redirects with curl or browser to confirm behavior.
Key Takeaways
Use a dedicated server block with
server_name www.example.com to catch www requests.Redirect with
return 301 https://example.com$request_uri; to preserve full URL and signal permanent redirect.Avoid using
rewrite for simple redirects; return is more efficient and clearer.Remember to handle HTTPS redirects separately if your site uses SSL.
Test your configuration to ensure users land on the correct non-www URL without losing path or query.