【问题标题】:Getting the remote ip address when using nginx proxy for Glang Gin?为 Golang Gin 使用 nginx 代理时获取远程 ip 地址?
【发布时间】:2022-12-10 02:08:52
【问题描述】:

我将 Nginx 用作使用 go gin 框架的 golang API 应用程序的代理
Nginx配置简单

server {
   listen 80;
   listen [::]:80;
   location / {
        proxy_pass  http://127.0.0.1:3000;
        proxy_set_header X-Client-IP $remote_addr;
        proxy_set_header  X-Appengine-Remote-Addr $remote_addr;
        add_header Access-Control-Allow-Origin *;
        proxy_set_header   Upgrade          $http_upgrade;
        proxy_set_header   Connection       upgrade;
        proxy_set_header   Accept-Encoding  gzip;
    }
}

Go 代码将 IP 地址存储到数据库使用

ctx.RemoteIP()

获取IP 问题是它总是存储 127.0.0.1 并且永远不会获得真正请求的 IP
我切换到另一个功能

ctx.ClientIP()

同样的问题它存储 127.0.0.1 而不是请求 IP

在这两种方法中,我确实将受信任的代理设置为“X-Client-IP”

func main() {
    r := gin.Default()
    r.TrustedPlatform = "X-Client-IP"
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pongy",
        })
    })
    r.POST("/signup", controllers.SignUp)
    r.POST("/login", controllers.Login)
    r.GET("/validation", middleware.RequireAuth, controllers.Validation)
    r.Run("127.0.0.1:3000") // listen and serve on 0.0.0.0:8080
}

【问题讨论】:

    标签: go nginx go-gin


    【解决方案1】:

    我相信你想做两件事来解决这个问题。

    首先,将标头名称从 X-Client-IP 更改为 X-Real-IPX-Forwarded-For

    然后,像这样将 localhost 设置为受信任的代理:

    r.SetTrustedProxies([]string{"127.0.0.1", "::1"})

    r.TrustedPlatform = "X-Client-IP" 行替换为上面的行,调用 ctx.ClientIP() 应该会返回您想要的内容。

    你可以在Gin source that it's looking for these two header names看到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-26
      • 2020-11-29
      • 1970-01-01
      • 2012-03-01
      • 2012-03-22
      • 2018-10-11
      • 2011-06-13
      • 1970-01-01
      相关资源
      最近更新 更多