NGINX背后的FastCGI应用程序无法检测到使用了HTTPS安全连接

时间:2011-01-31 07:13:48

标签: django nginx fastcgi

我在Nginx后面运行FastCGI,需要检测何时通过HTTPS访问url。但是,我的Django Web应用程序始终报告连接是HTTP(request.is_secure()== False)。但是,SSL已正确设置,我已通过SSL检查器验证了我的https://网址是否安全。

如何让Django正确检测请求何时来自HTTPS网址?

我的Nginx设置为:

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    gzip  on;

    server {
        listen       80;
        listen       443 default ssl;
        ssl_certificate   /home/webapp/ssl.crt
        ssl_certificate_key /home/webapp/ssl.key

        server_name  myapp.com;
        access_log /home/webapp/access.log
        error_log  /home/webapp/error.log

        root   /home/mywebapp;

        location / {
               # host and port to fastcgi server                      
           fastcgi_pass 127.0.0.1:8801;
           fastcgi_param PATH_INFO $fastcgi_script_name;
           fastcgi_param REQUEST_METHOD $request_method;
           fastcgi_param QUERY_STRING $query_string;
           fastcgi_param SERVER_NAME $server_name;
           fastcgi_param SERVER_PORT $server_port;
           fastcgi_param SERVER_PROTOCOL $server_protocol;
           fastcgi_param CONTENT_TYPE $content_type;
           fastcgi_param CONTENT_LENGTH $content_length;
           fastcgi_pass_header Authorization;
           fastcgi_intercept_errors off;
        }
    }
}

我用:

启动Django FastCGI流程
python /home/webapp/manage.py runfcgi method=threaded host=127.0.0.1 port=8801 pidfile=/home/webapp/fastcgi.pid 

2 个答案:

答案 0 :(得分:30)

感谢Yuji的回答。我已更新我的服务器块以有条件地注入HTTPS或关闭HTTPS,具体取决于$ server_port:

{

server {
    listen       80;
    listen       443 default ssl;

    if ($server_port = 443) { set $https on; }
    if ($server_port = 80) { set $https off; }

    ssl_certificate   /home/webapp/ssl.crt
    ssl_certificate_key /home/webapp/ssl.key

    server_name  myapp.com;
    access_log /home/webapp/access.log
    error_log  /home/webapp/error.log

    root   /home/mywebapp;

    location / {
           # host and port to fastcgi server                      
       fastcgi_pass 127.0.0.1:8801;
       fastcgi_param PATH_INFO $fastcgi_script_name;
       fastcgi_param REQUEST_METHOD $request_method;
       fastcgi_param QUERY_STRING $query_string;
       fastcgi_param SERVER_NAME $server_name;
       fastcgi_param SERVER_PORT $server_port;
       fastcgi_param SERVER_PROTOCOL $server_protocol;
       fastcgi_param CONTENT_TYPE $content_type;
       fastcgi_param CONTENT_LENGTH $content_length;
       fastcgi_pass_header Authorization;
       fastcgi_intercept_errors off;

       fastcgi_param HTTPS $https;
    }
}

}

答案 1 :(得分:13)

确保nginx正在为443上的连接发送fastcgi_param HTTPS on