Post Date: March 3, 2017
Last Updated: September 28, 2026
Introduction
In this post, we will explain how to configure Nginx to redirect all non-www requests to the www version of a domain. This configuration ensures that visitors accessing the website without the www prefix are automatically redirected to the corresponding www URL.
Prerequisites
Before implementing this configuration, ensure that:
- Nginx is installed and running on the server.
- You have root or sudo access to the server.
- A valid domain name is configured and pointing to the server.
- You have access to the Nginx configuration file located at
/etc/nginx/sites-enabled/default. - If Nginx is not installed, refer to the installation guides for Ubuntu 16.04 or CentOS 7 mentioned in this post.
Implementation
The default Nginx configuration file is /etc/nginx/sites-enabled/default.
Open the Nginx configuration and add the following lines.
vi /etc/nginx/sites-enabled/default
server {
listen 80;
server_name domain.tld;
return 301 http://www.domain.tld$request_uri;
}
Check for syntax errors
nginx -t
If there are no errors, restart the nginx service to make the changes take effect.
/etc/init.d/nginx restart
Conclusion
By adding the appropriate server block to the Nginx configuration, all non-www requests can be automatically redirected to the www version of the domain. After updating the configuration, use nginx -t to verify the syntax and restart Nginx to apply the changes. This provides a consistent URL format for accessing the website.
FAQs
1. Why should I redirect non-www requests to www?
Redirecting non-www requests to www ensures that visitors consistently access the website using a single URL format.
2. Where is the default Nginx configuration file located?
On Ubuntu systems, the default Nginx configuration is generally located at /etc/nginx/sites-enabled/default.
3. How can I check whether the Nginx configuration has any errors?
Run the following command:
nginx -t
If the configuration is correct, Nginx will report that the syntax is OK.
Related Articles
Redirect http to https on nginx behind load balancers
Talk to our experts
Looking for the right technology solution for your business?. Our experts can help with web hosting, domain registration, DevOps and cloud, software development, web applications, mobile applications, and enterprise solutions. Get in touch with our team here.