Make http redirect to https

I can’t work out if I have a problem with my nginx or django settings. I’m trying to redirect www.example.com to https://example.com but get the not secure browser warning. Https is working fine.

In settings.py I have:

SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = "DENY"
SECURE_HSTS_SECONDS = 3600 
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True

my nginx .conf file has:

upstream myapp_app_server {
    server unix:/webapps/myapp/myapp_env/run/gunicorn.sock fail_timeout=0;
}


server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com-0001/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com-0001/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    client_max_body_size 4G;

    access_log /etc/nginx/logs/nginx-access-prod.log;
    error_log /etc/nginx/logs/nginx-error-prod.log;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {
        alias /var/www/html/myapp/static/;

    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        if (!-f $request_filename) {
            proxy_pass http://myapp_app_server;
            break;
        }

        if ( $host !~* ^(example.com|www.example.com)$ ) {
            return 444;
        }
    }
}

One solution I thought of is to just add a separate https certificate for www.example.com but it seems most other people on stack overflow or tutorials don’t have to do that. Is there anything wrong with having two ssl certificates for www and non-www?

Is your let’s encrypt certificate a wildcard certificate ? *.example.com ?

In


server {
    listen 443 ssl http2;
    server_name example.com;
    ...

you should also have www.example.com


server {
    listen 443 ssl http2;
    server_name example.com www.example.com;
    ...
1 Like

Additionally, if you click on the lock icon and dig into the information presented there, it’ll tell you why it’s thinking it’s insecure.

1 Like