首页 > 解决方案 > HTTPS 协议不适用于 ec2 实例上的 django 和 nginx

问题描述

我一直在尝试在 ec2 实例中使用 django 中的 nginx 将所有请求自动传输到 https 协议,但我无法这样做..这是我的 nginx 文件..请向我提出问题。

nginx 文件

server{
listen 443 ssl;
server_name www.priyamarya.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/ubuntu/project/aryapriyam/;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/ubuntu/project/aryapriyam/project.sock;
    }
}
server{
listen 80;
server_name priyamarya.com;
return 301 https://www.priyamarya.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/ubuntu/project/aryapriyam/;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/ubuntu/project/aryapriyam/project.sock;
    }
}

我还在settings.py中添加了这个

设置.py

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT =True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

gunicorn.service

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/project/aryapriyam
ExecStart=/home/ubuntu/project/venv/bin/gunicorn --access-logfile - -- 
workers 3 --chdir /home/ubuntu/project/aryapriyam/ --bind 
unix:/home/ubuntu/project/aryapriyam/project.sock 
project.wsgi:application

[Install]
WantedBy=multi-user.target

我还将我的 hostszone A 类型记录集设置为 elb 负载均衡器提供的别名。

我已经尝试了很多事情,比如返回https://sitename,并为这两种协议创建不同的服务器块,但它会在请求之间启动一个循环。这就是为什么我要发布我最初开始的代码。我进行了很多搜索,但对于 nginx 和 django 都没有任何帮助,请帮助.. 我希望我的所有表单请求也只能通过 https。

标签: djangoamazon-web-servicesnginxamazon-ec2https

解决方案


您需要为 ssl 添加其他服务器块并为 ssl 使用以下配置

http此配置还将请求重定向到https即 ssl 端口 443

server {
    listen 80;
    server_name testing.com;
    return 301 https://testing.com;
    location = /favicon.ico { access_log off; log_not_found off; }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/ubuntu/sample_project/sample_project.sock;
    }
}

server {
   listen 443 ssl;
   listen [::]:443 ssl;
   server_name testing.com;

   ssl on;
   ssl_certificate /etc/nginx/ssl/nginx.crt;
   ssl_certificate_key /etc/nginx/ssl/nginx.key;
   location /static/ {
           root /home/ubuntu/sample_project;
      }
   location / {
         include proxy_params;
         proxy_pass http://unix:/home/ubuntu/sample_project/sample_project.sock;
       }

}

推荐阅读