'Redirect WWW to Non WWW not working (CERTBOT, NGINX, GUNICORN, FLASK)

I recently came into an issue with Flask-WTF where I needed to set a SERVER_NAME in config for the app so the CSRF tokens could work. This worked great but now I can't see my python loaded work without going to the correct domain that I put into the SERVER_NAME env variable. My solution to this in my mind would be to redirect from www.websitename.com to websitename.com. However creating a /etc/nginx/conf.d/redirect.conf with these contents:

server {
    server_name www.websitename.com;
    return 301 $scheme://websitename.com$request_uri;
}

and having /etc/nginx/sites-enabled/webapp contain:

server {
        server_name websitename.com www.websitename.com;

        location /static {
                alias /home/sai/webapp/website/static;
        }

        location / {
                proxy_pass http://localhost:8000;
                include /etc/nginx/proxy_params;
                proxy_redirect off;
        }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/www.websitename.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.websitename.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 = websitename.com) {
        return 301 https://$host$request_uri;
    } #managed by Certbot

        listen 80;
        server_name websitename.com
    return 404;
}

server {
    if ($host = www.websitename.com) {
        return 301 https://websitename.com$request_uri;
    }
        listen 80;
        server_name www.websitename.com
    return 404;
}

doesn't work. I still don't get redirected and I still can't see any gunicorn content.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source