Redirecting from www to non-www with Nginx (301 Redirect)
What will you learn in this guide?
In this guide, you will learn how to permanently redirect www domain name to non-www domain on Ubuntu servers using Nginx.
You will establish the 301 redirect structure, which is correct in terms of SEO, and collect your domain name under a single canonical address.
Technical Summary (Phase 1)
This guide solves the domain consistency issue on Nginx.
The aim is to collect www and non-www requests at a single address and increase SEO power.
Steps: DNS records → Nginx server block → 301 redirect → test.
1. Configure DNS Records
First, both versions of the domain name must reach the server.
- A register for
example.com - A register for
www.example.com
Both records should show the IP address of the server.
This process ensures that Nginx can capture both requests.
2. Edit Server Block for Main Site
If your main domain will be non-www, the configuration should only include that.
server {
server_name example.com;
}
- This structure defines the real address of the site.
3. Create 301 Redirect Server Block for www
- Now we will capture www requests and redirect them to non-www.
sudo nano /etc/nginx/sites-available/www.example.com.conf
- This command opens a new Nginx configuration file for www.
server {
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
This structure:
-
Applies permanent redirect
-
Preserves the URL path
-
Creates canonical address for SEO
4. Enable Configuration
sudo ln -s /etc/nginx/sites-available/www.example.com.conf /etc/nginx/sites-enabled/
- This command activates the configuration to Nginx.
5. Test Configuration
sudo nginx -t
- This command checks for syntax errors in Nginx configuration.
If successful, reinstall Nginx:
sudo systemctl reload nginx
- This command applies new settings without interruption.
6. Verify Redirection
curl -IL http://www.example.com
- This command shows HTTP headers and redirect chain.
Expected output:
-
First answer: 301 Moved Permanently
-
Second answer: 200 OK
Frequently Asked Questions (FAQ)
1. Why should I use 301 redirect? 301 redirect tells search engines that the address is permanent.
2. Is www or non-www better? There is no difference in terms of SEO. The important thing is to use a single address.
3. If I use HTTPS, does the structure change? No. The $scheme variable automatically handles HTTP and HTTPS.
4. Isn't it possible if two domain names work without redirect? It is possible, but the SEO power will be divided and the ranking may decrease.
5. Will it work even if I use a reverse proxy? Yes. This structure works smoothly in front of the proxy.
Result
- With this configuration:
-
Your domain name becomes unique
-
SEO power is maintained
-
User experience is not disrupted
You can try GenixNode solutions now to manage your Nginx-based projects with correct guidance, high performance and clean infrastructure.

