How to Force Nginx to Redirect Site Name "Without-www" to "www"?

nginx redirect non www to www

If you have a domain, 'example.com' and you want it to be available both when a user enters, 'http://example.com' and 'http://www.example.com', and you are running Nginx on your server, you can do so by updating the Nginx conf file for that Site. This file can usually be found in /etc/nginx/sites-available/ folder.
Open the file and add a new 'Server' Block on the top.

To redirect, site name with www to without www :

server {
    listen 80;
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

Replace the www.example.com above with your domain name (with 'www' ofcourse )

To redirect site name, without-www to www :

server {
    listen 80;
    server_name example.com;
    return 301 $scheme://www.example.com$request_uri;
}

Similarly, replace 'example.com' with the domain name (without www)

Save the file and test the nginx configuration, before restarting Nginx and applying the new configuration :

nginx -t

If this shows no errors, then restart Nginx to apply the settings :

service nginx restart
© 2024 WPOven Inc. All rights reserved. WPOven® and WordPress® are registered trademarks.
WPOven is the best Managed WordPress hosting for agencies and businesses that want to succeed. With Unlimited sites hosting option, its easy to use and manage, so you can focus on growing your business. 
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram