Report this

What is the reason for this report?

NGINX redirect www to non-www

Posted on November 12, 2018

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
}



This textbox defaults to using Markdown to format your 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.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.