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!
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.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.