Question

NGINX redirect www to non-www

Hi there, I am trying to redirect all NGINX www paths to non-www. Does anybody know how to do it?

server {
	root /var/www/mydomain.com/html;
	index index.html index.htm index.nginx-debian.html;

	server_name mydomain.com www.mydomain.com;
	
	#Certbot stuff here...
}

server {
    if ($host = www.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


	listen 80;
	listen [::]:80;

	server_name mydomain.com www.mydomain.com;
    return 404; # managed by Certbot
}

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

I’m brand new to nginx and just ran into this problem myself and spent some hours trying to figure it out. My solution feels hacky and theres probably a better way to do this, but it got it working on my server.

In the first ‘server’ block, right below the server names I added a conditional for a redirect. Here’s what it would look like using your code.

server {
    root /var/www/mydomain.com/html;
    index index.html index.htm index.nginx-debian.html;

    server_name mydomain.com www.mydomain.com;


    if ($host = www.mydomain.com) {
        return 301 https://mydomain.com$request_uri;
    }

    #Certbot stuff here...
}

If someone knows of or finds a better way to do this, please leave a comment.