gpt4 book ai didi

python - django:使用 NGINX 的 SECURE_SSL_REDIRECT 应用程序崩溃

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:03 25 4
gpt4 key购买 nike

我正在尝试使用 nginx、gunicorn 让我的 django 应用程序在 SSL 背后工作;都安装在一个可以在内网访问但不能从外部访问的服务器上。这些是我的设置。

设置.py:

...
SECURITY_MIDDLEWARE = ('django.middleware.security.SecurityMiddleware',)
MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'SAMEORIGIN'
SECURE_HSTS_SECONDS = 60
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_CONTENT_TYPE_NOSNIFF = True

SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

nginx.conf:

server {
listen 80;
server_name HOSTNAME;

location / {
proxy_set_header Host $host;
proxy_pass http://unix:/tmp/HOSTNAME.socket;
proxy_set_header X-Forwarded-Protocol $scheme;
rewrite ^ https://$host/$request_uri permanent;
}
}

想知道是否有人可以指出我正确的解决方案。

最佳答案

免责声明:我是网络开发新手。我也是问题的作者。

编辑:在/var/log/nginx/HOSTNAME_error.log 中我收到以下错误:

no "ssl_certificate" is defined in server listening on SSL port while SSL handshaking

基于史蒂夫的回答、这个问题(见链接的评论)和这个 blog ,我终于让我的应用程序支持 SSL。

我使用以下命令创建了 SSL 证书和 key (像我这样没有经验的用户应该注意这些证书是自签名的,因此浏览器将连接归类为不安全连接。但是交易已正确加密。有关命令的更多信息,请参阅blog ):

dzdo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt

将我的 nginx.conf 更改为(因为我使用的是 DjangoWhiteNoise,我的 nginx conf 不处理静态媒体文件):

server {
listen 80;
server_name HOSTNAME;
rewrite ^/(.*) https://HOST/$1 permanent;
}

server {
listen 443 ssl;
server_name HOSTNAME;
access_log /var/log/nginx/HOSTNAME_access.log combined;
error_log /var/log/nginx/HOSTNAME_error.log error;

# To create an SSL certificate:
# dzdo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt

ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;

location / {
proxy_pass http://unix:/tmp/HOST.socket;
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}

}

最后,我将我的 Django 安全设置设置为:

...
SECURITY_MIDDLEWARE = ('django.middleware.security.SecurityMiddleware',)
MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'SAMEORIGIN'
SECURE_HSTS_SECONDS = 60
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_CONTENT_TYPE_NOSNIFF = True

SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

希望这可以帮助像我这样的人。

关于python - django:使用 NGINX 的 SECURE_SSL_REDIRECT 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33792940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com