Redirecting non-www to www URLs in Nginx is a common configuration to ensure that your website consistently uses one canonical URL format. This can help with SEO and ensure that all visitors are directed to a single version of your site. Here’s how to set up this redirection:
1. Access Your Nginx Configuration File:
You can usually find your Nginx server block configuration file in the /etc/nginx/sites-available/ directory on Linux-based systems. Open your configuration file with a text editor:
sudo nano /etc/nginx/sites-available/your-site.confReplace your-site.conf with the actual name of your configuration file.
2. Add a Server Block for Non-WWW to WWW Redirect:
Inside the server block for your domain, add a new server block to handle non-www to www redirection. Here’s an example:
server {
listen 80;
server_name your-domain.com;
return 301 $scheme://www.your-domain.com$request_uri;
}listen 80;specifies that this server block listens on port 80 (HTTP).server_name your-domain.com;should match your domain without the “www” prefix.return 301issues a permanent (HTTP 301) redirect.$scheme://www.your-domain.com$request_uriconstructs the URL to which non-www requests will be redirected. It ensures that the request URI is preserved during the redirect.
3. Update the Existing Server Block:
In the existing server block for your domain (the one that handles www requests), make sure it listens on both non-www and www versions of your domain. For example:
server {
listen 80;
server_name your-domain.com www.your-domain.com;
# Your other server configuration directives go here
}This configuration block listens for both non-www and www requests on port 80.
4. Test and Reload Nginx:
Before applying the changes, test your Nginx configuration to ensure there are no syntax errors:
sudo nginx -tIf the test is successful, reload Nginx to apply the configuration changes:
sudo systemctl reload nginx5. Verify the Redirection:
Open a web browser and try accessing your site using the non-www URL (e.g., http://your-domain.com). You should be automatically redirected to the www version (e.g., http://www.your-domain.com). Verify that the redirection works correctly.
By following these steps, you can configure Nginx to redirect non-www URLs to www URLs, ensuring a consistent URL structure for your website.