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.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Scale up as you grow — whether you're running one virtual machine or ten thousand.

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.
