0
votes

I have a Django project already using AWS SSL certificate from the Certificate Manager service. My application is accessible via HTTPS, however, it isn't redirecting automatically when accessing via HTTP.

My Nginx default.conf file before redirect (works like a charm!):

upstream django {
    server my_app:8000;
}

server {

    location / {
        proxy_pass http://django;
    }
}

After setting up the redirect:

upstream django {
    server my_app:8000;
}

server {
    listen 80;
    if ($http_x_forwarded_proto = 'http'){
        return 301 https://$host$request_uri;
    }

    location / {
        proxy_pass http://django;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

And here is my Django settings.py for this:

.
.
.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

CORS_ORIGIN_ALLOW_ALL = True

CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 340505040
SECURE_SSL_REDIRECT = True
.
.
.

Then I'm getting http 400 (this is the Load Balancer Health Checker):

shell_print

Edit 1

With this new setup, I'm getting http 301:

upstream django {
        server my_app:8000;
}

server {
        listen 80;
        location / {
                proxy_pass http://django/;
                if ($http_x_forwarded_proto != 'https') {
                        rewrite ^ https://$host$request_uri? permanent;
                }
        }
}

I've been looking around and didn't find any example that helps me. What can I try next?

1

1 Answers

0
votes

On NGINX config put all the sites on SSL only

site on SSL

nginx/sites-available/sitex only listens to port 443

server {
    # SSL configuration
    #
    listen 443 ssl ;
    listen [::]:443 ssl ;

    ssl_certificate /etc/letsencrypt/live/www.sitex.nl/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.sitex.cops.nl/privkey.pem; # managed by Certbot

    server_name www.sitex.com; # managed by Certbot

    access_log  /var/log/nginx/sitex_access.log;
    error_log   /var/log/nginx/sitex_error.log;

    location / {
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        add_header      Access-Control-Allow-Origin *;
        proxy_pass      http://127.0.0.1:8004;
    }
}

All SSL/TLS requests to www.sitex.com are forwarded to localhost:8004.

And the SiteX Docker Image is picking up on that port.

nginx.conf

In the nginx.conf file the Virtual Hosts section is as follows

##
# Virtual Host Configs
##

include /etc/nginx/all_http_to_https.conf;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

all_http_to_https.conf

This file does the trick

server {
    listen 80 default_server;

    server_name _;

    return 301 https://$host$request_uri;
}