Nginx反向代理到Yesod转发的IP地址不起作用

时间:2020-10-09 07:43:50

标签: nginx nginx-reverse-proxy yesod

我已将nginx设置为Yesod的反向代理。 /var/log/nginx/access.log中的IP地址是客户端的真实IP地址。

123.123.123.123 - - [09/Oct/2020:07:11:16 +0000] "GET / HTTP/1.1" 200 ...

但是Yesod在日志中显示的IP地址是nginx的127.0.0.1。

127.0.0.1 - - [09/Oct/2020:07:11:16 +0000] "GET / HTTP/1.0" 200 - "https://...

这是我的nginx配置:

... 
server {

        server_name example.com;

        location / { 

            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;

            proxy_pass http://127.0.0.1:3000; # Reverse proxy to your Yesod app 
        }   

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
...

我已经重新启动了nginx和yesod二进制文件。但是Yesod列出的IP仍然是127.0.0.1。

我犯了什么配置错误?

还是我需要编辑Yesod二进制文件的日志记录代码?

谢谢各位读者

1 个答案:

答案 0 :(得分:0)

答案是,Yesod有一个配置选项可以使用转发的IP标头。

我通过阅读src/Settings.hs找到了它,它包含以下内容:

data AppSettings = AppSettings
    { appStaticDir              :: String
    -- ^ Directory from which to serve static files.
    , appDatabaseConf           :: PostgresConf
    -- ^ Configuration settings for accessing the database.
    , appRoot                   :: Maybe Text
    -- ^ Base for all generated URLs. If @Nothing@, determined
    -- from the request headers.
    , appHost                   :: HostPreference
    -- ^ Host/interface the server should bind to.
    , appPort                   :: Int
    -- ^ Port to listen on
    , appIpFromHeader           :: Bool
    -- ^ Get the IP address from the header when logging. Useful when sitting
    -- behind a reverse proxy.
...

因此,您需要编辑包含以下行的config/settings.yaml

...
ip-from-header: "_env:YESOD_IP_FROM_HEADER:false" 
...

或者,您也可以运行此命令export YESOD_IP_FROM_HEADER=true来更改环境变量。

解决了。

相关问题