因此,我使用 nginx 进行了简单的设置,用于静态媒体和负载平衡,使用龙卷风作为 django 的网络服务器(4 个服务器正在运行)。我的问题是remote_addr没有传递给django所以我得到一个KeyError:

article.ip = request.META['REMOTE_ADDR']

由于 nginx.conf,远程地址以 X-Real-IP (HTTP_X_REAL_IP) 的形式发送:

    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect false;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://frontends;
    }

由于 HTTP 被添加到 META 键之前,我不能只执行 proxy_set_header remote_addr $remote_addr 。如果没有找到远程地址密钥,我能做的就是读取 X-Real-IP,但我很好奇是否有更智能的解决方案。

谢谢!

有帮助吗?

解决方案

试试这个:

location / {
    proxy_pass http://frontends;
    proxy_pass_header Server;
    proxy_redirect off;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_set_header REMOTE_ADDR $remote_addr;
}

只需添加 proxy_set_header REMOTE_ADDR 它应该工作得很好。

尝试过:

  • 姜戈 1.5.4
  • nginx 1.4.3
  • 龙卷风2.2.1

其他提示

以下是我解决问题的方法。通过使用此中间件:

class SetRemoteAddrMiddleware(object):
    def process_request(self, request):
        if not request.META.has_key('REMOTE_ADDR'):
            try:
                request.META['REMOTE_ADDR'] = request.META['HTTP_X_REAL_IP']
            except:
                request.META['REMOTE_ADDR'] = '1.1.1.1' # This will place a valid IP in REMOTE_ADDR but this shouldn't happen

希望有所帮助!

我有类似的设置。将nginx放在apache之前后,我注意到apache日志中的IP始终为127.0.0.1。安装“libapache2-mod-rpaf”似乎解决了这个问题。我不知道你的问题是否相关。

添加" fastcgi_param REMOTE_ADDR $ remote_addr;"到nginx.conf文件:

    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 CONTENT_TYPE $content_type;
    fastcgi_param CONTENT_LENGTH $content_length;
    fastcgi_pass_header Authorization;
    fastcgi_intercept_errors off;
    ...
    # Add this line!
    fastcgi_param REMOTE_ADDR $remote_addr;
    ...
}

来源:如何为django提供nginx虚拟服务器+ fcgi?

对我来说,使用以下工作:

server {
    listen 80;
    server_name foo.bar.com;
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}

这适用于django 1.4(特别是localshop)。

不,无法传递remote_addr。因此,我所知道的唯一解决方案是使用X-Real-IP或X-Forwarded-For,并确保后端正确处理这些。

编辑:这适用于fastcgi_pass,而非常规nginx proxy_pass

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top