Trying to redirect non-www to www (Certbot, Nginx), but the opposite occurs. What's causing this?

I want to redirect all domain traffic to

Instead, everything is going to

I’m not sure what I’m doing wrong. Any help would be greatly appreciated!

server {

  root /var/www/;
  index index.html index.php index.htm index.nginx-debian.html;


  location / {
    #try_files $uri $uri/ =404;
    try_files $uri $uri/ /index.php$is_args$args;

  location = /favicon.ico { log_not_found off; access_log off; }
  location = /robots.txt { log_not_found off; access_log off; allow all; }
  location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
    expires max;
    log_not_found off;

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;

  location ~ /\.ht {
    deny all;

  listen [::]:443 ssl; # managed by Certbot
  listen 443 ssl; # managed by Certbot
  ssl_certificate /etc/letsencrypt/live/; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


server {

  return 301 https:///$request_uri;

  listen 80;
  listen [::]:80;

  return 404; # managed by Certbot


Submit an answer

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!

Sign In or Sign Up to Answer

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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Your configuration should route all http traffic to but will not redirect to unless you define a seperate server block for the non-www version.

That does not however, explain things redirecting from http to but I have a guess about what may. By any chance are you running WordPress on this site? In addition to the redirects in your Nginx configuration, WordPress does it’s own redirecting.

When you first configure WordPress it will use the URL used to set up it’s default URL setting (this is under the main site settings in wp-admin). So if you first configured WordPress by going to it will use as it’s base URL and redirect any requests for other URLs to that.

Note that you should check and address this WordPress setting if relevant before you add the non www to www redirect I mentioned. Doing so before updating your WordPress settings could cause a redirect loop between Nginx and WordPress.