How to Redirect Non-WWW to WWW in Nginx
To redirect non-www to www in
nginx, create a server block for the non-www domain that uses a return 301 directive to send visitors to the www version. This ensures all traffic to example.com is permanently redirected to www.example.com.Syntax
The basic syntax to redirect non-www to www in Nginx involves creating a server block for the non-www domain and using the return 301 directive to redirect to the www domain.
server_name: Specifies the domain to match (non-www).return 301: Sends a permanent redirect status code.$scheme: Keeps the original request protocol (http or https).$host: The requested host name, replaced here with www domain.$request_uri: The full original request path and query string.
nginx
server {
listen 80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}Example
This example shows a complete Nginx configuration that redirects all requests from example.com to www.example.com. It listens on port 80 and issues a permanent redirect preserving the original path and query.
nginx
server {
listen 80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
location / {
root /var/www/html;
index index.html;
}
}Output
When a user visits http://example.com/page, the browser receives a 301 redirect to http://www.example.com/page.
Common Pitfalls
Common mistakes when redirecting non-www to www in Nginx include:
- Forgetting to specify the correct
server_namefor the non-www domain. - Using
rewriteinstead ofreturn 301, which is less efficient. - Not preserving the original request URI, causing users to lose the requested page path.
- Missing the
$schemevariable, which can cause protocol mismatches.
nginx
Wrong way:
server {
listen 80;
server_name example.com;
rewrite ^/(.*)$ http://www.example.com/$1 permanent;
}
Right way:
server {
listen 80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| server_name | Defines the domain to match | server_name example.com; |
| return 301 | Sends permanent redirect | return 301 $scheme://www.example.com$request_uri; |
| $scheme | Preserves http or https | $scheme://www.example.com |
| $request_uri | Preserves full path and query | $request_uri |
Key Takeaways
Use a separate server block for the non-www domain to handle redirection.
Use 'return 301' for efficient permanent redirects instead of 'rewrite'.
Always preserve the original request URI to keep user navigation intact.
Include '$scheme' to maintain the original protocol (http or https).
Test your configuration with 'nginx -t' and reload Nginx after changes.