django - 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。
解决方案
您需要为 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;
}
}
推荐阅读
- entity-framework - 在保存上下文之前,Entity Framework Core 如何处理实例?
- shell - 如何从大文件中获取最小前缀
- swift - 如何从 Sqlite swift 中删除表视图行?
- angular - 节点模块文件缺少括号 - 这是一个全球性问题吗?它可以修复吗?
- list - 有没有办法用 java 8 流更改 dateFormat ?
- java - 为什么我对位于 /data/user_de/ 的文件的权限被拒绝
- swagger - Open API中API ID和API名称的区别?
- c# - 目前,按钮或标签等工具也不可用。有没有办法解决这个问题?
- sparql - 如何改善 DBpedia Spotlight 的结果?
- r - Shiny Dashboard 中 Google Analytics API 的身份验证范围问题