NGINX – conflicting server name “www.foo.com” on 0.0.0.0:80, ignored

I can’t figure out why does nginx raises error conflicting server name.

My project runs on two domains – foo.com and bar.com. After setting up nginx, I’ve installed let's encrypt certificate which adds a server block in sites-available/myproject.

Then I tried to set redirects from www.foo.com and www.bar.com to foo.com and bar.com but these two domains doesn’t work.

sudo nginx -t nginx: [warn] conflicting server name "www.foo.com" on 0.0.0.0:80, ignored nginx: [warn] conflicting server name "www.bar.com" on 0.0.0.0:80, ignored nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful 

The same shows error.log

This is the sites-available/myproject

server {     listen 80;     server_name www.bar.com;     return 301 $  scheme://bar.com$  request_uri; }  server {     listen 80;     server_name www.foo.com;     return 301 $  scheme://foo.com$  request_uri; }  server {     server_name foo.com bar.com;      location = /favicon.ico { access_log off; log_not_found off; }     location /static/ {         root /home/futilestudio/myproject;     }      location / {         include proxy_params;         proxy_pass http://unix:/run/gunicorn.sock;     }      listen 443 ssl; # managed by Certbot     ssl_certificate /etc/letsencrypt/live/foo.com/fullchain.pem; # managed by Certbot     ssl_certificate_key /etc/letsencrypt/live/foo.com/privkey.pem; # managed by Certbot     include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot     ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot     }  server {     if ($  host = bar.com) {         return 301 https://$  host$  request_uri;     } # managed by Certbot       if ($  host = foo.com) {         return 301 https://$  host$  request_uri;     } # managed by Certbot       listen 80;     server_name 178.128.xxx.xxx foo.com bar.com;     return 404; # managed by Certbot     } 

So what I want is to redirect all www to non-www which are secured. Do you know where is the problem?