gru*_*iba 6 python django nginx amazon-ec2 web-deployment
我刚刚使用 nginx 在 AWS 上部署了 django 项目。一切正常,除了当我尝试发出任何 POST 请求(仅通过 http)时,我收到错误:
“禁止 (403) CSRF 验证失败。请求已中止。”
如果我直接使用 Django 运行我的服务器,CSRF 验证就会起作用,这让我认为我没有nginx.conf正确设置我的服务器。
有人可以指导我如何配置 nginx 来使用 csrf 吗?
这是我当前的配置:
#nginx.conf
upstream django {
# connect to this socket
server unix:///tmp/uwsgi.sock; # for a file socket
#server 127.0.0.1:8001; # for a web port socket
}
server {
# the port your site will be served on
listen 80;
root /opt/apps/site-env/site;
# the domain name it will serve for
server_name mysite.org
charset utf-8;
#Max upload size
client_max_body_size 75M; # adjust to taste
location /media {
alias /opt/apps/site-env/site/media;
}
location /static {
alias /opt/apps/site-env/site/static;
}
location / {
uwsgi_pass django;
include /etc/nginx/uwsgi_params;
proxy_pass_header X-CSRFToken;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto http;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header HOST $http_host;
proxy_set_header X-NginX-Proxy true;
}
}
Run Code Online (Sandbox Code Playgroud)
我还在我的 django 设置中关闭了SESSION_COOKIE_SECURE和。CSRF_COOKIE_SECURE
谢谢
当您从 javascript 发布帖子时,请确保将其settings.CSRF_COOKIE_HTTPONLY设置为False
[1] 中的片段:“是否在 CSRF cookie 上使用 HttpOnly 标志。如果将其设置为 True,客户端 JavaScript 将无法访问 CSRF cookie。”
[1] https://docs.djangoproject.com/en/2.0/ref/settings/#csrf-cookie-httponly