我的 Ubuntu 20.10 服务器安装了 Nginx + Gunicorn + Django。已安装 SSL 证书并通过了多项在线 SSL/TLS 测试评估。它仍然在浏览器中显示为未锁定。 Whynopadlock 表示需要强制使用 HTTPS。该命令返回 301 https://$server_name$request_uri;破坏网站 - 无限重定向。
有人可以提供建议吗?站点可用配置发布在下面。已经尝试了以下数十种变体,但均无济于事:
#Have tried with and without this:
upstream django {
server 127.0.0.1:8000;
keepalive 32;
}
#Have tried with and without this
#server {
# listen 80 default_server;
# server_name www.example.com;
# return 301 https://$server_name$request_uri; #This line breaks site if 1 or 2 server blocks are used
#}
server {
listen 80; #Removed this for above server block
listen 443 ssl;
server_name www.example.com; #Removed www.*
ssl_certificate /etc/nginx/ssl/certificate.crt;
ssl_certificate_key /etc/nginx/ssl/private.key;
ssl_protocols TLSv1.2 TLSv1.3;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
alias /home/ubuntu/example/staticfiles/;
}
location / {
#Tried many combinations of these:
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
#proxy_set_header Host $host;
proxy_set_header Host $http_host; #Have tried $http and $http_host
proxy_set_header Connection "";
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://unix:/run/gunicorn.sock; #Have tried variations on this with and without trailing'/'
# and with http and https
break;
}
}
}
最佳答案
对于我的项目,我使用以下内容:
upstream django_server {
server 172.27.0.1:8000;
}
# Redirect HTTP to HTTPS.
server {
listen 80 default_server;
server_name www.example.com example.com;
location / {
return 301 https://example.com$request_uri;
}
}
server {
listen 443 ssl;
server_name example.com www.example.com;
location / {
proxy_pass http://django_server;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Real-IP $remote_addr;
}
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
关于django - Nginx 返回 301 https ://$server_name$request_uri; Too Many Redirects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67538722/