【问题标题】:Go server with nginx reverse proxy使用 nginx 反向代理转到服务器
【发布时间】:2018-09-10 15:24:03
【问题描述】:

我一直在尝试建立一个使用 docker 和 nginx 作为反向代理的 go web 应用程序。

我的计划是为多个应用程序使用一个域,例如:mydomain.com/myapp1

但是,每当我尝试使用 localhost/myapp/something 之类的 URL 访问我的应用程序时,请求就会被重定向到 http://localhost/something

我经历了各种 nginx 配置,但都没有工作,所以我怀疑问题出在路上。

在应用程序本身中,我使用 gorilla mux 进行路由,还使用 ​​negroni 进行一些中间件。

相关代码如下所示:

baseRouter := mux.NewRouter()
baseRouter.HandleFunc("/something", routes.SomeHandler).Methods("GET")
baseRouter.HandleFunc("/", routes.IndexHandler).Methods("GET")

commonMiddleware := negroni.New(
    negroni.HandlerFunc(middleware.Debug),
)

commonMiddleware.UseHandler(baseRouter)
log.Fatal(http.ListenAndServe(":5600", commonMiddleware))

据此,每个请求都应该通过我的调试中间件,它只是将一些请求信息打印到标准输出,但是当重定向发生时,它就不起作用了。

但如果路径不匹配任何处理程序,一切正常,标准 go 404 消息按预期显示,并且调试中间件也会打印请求。

我的 GET 处理程序通常只做这样的事情:

templ, _ := template.ParseFiles("public/something.html")
templ.Execute(w, utils.SomeTemplate{
    Title: "something",
})

最后,我的 nginx 配置中的相关部分:

server {
    listen 80;
    server_name localhost;

    location /myapp/ {
        # address "myapp" is set by docker-compose
        proxy_pass http://myapp:5600/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_cache_bypass $http_upgrade;
    }
}

这种 nginx 配置过去对于 nodeJS 应用程序来说已经足够了,所以我不明白为什么它不起作用。如果有人能指出我到底做错了什么,我将不胜感激。

【问题讨论】:

  • 您也应该在 golang 中使用基本 url 以避免出现问题。然后你应该在你的nginx中将baseRouter := mux.NewRouter()更改为baseRouter := mux.NewRouter().PathPrefix("/myapp"),并将proxy_pass http://myapp:5600/;更改为proxy_pass http://myapp:5600;,这样/myapp也会发送到golang服务器
  • 是的,谢谢,我现在知道了。为其他在这些事情上苦苦挣扎的人提供的建议:删除您的浏览器缓存,或完全禁用它......显然我的请求甚至没有到达服务器,因为某种原因,Firefox 施展了它的黑魔法。

标签: docker nginx go


【解决方案1】:

您的 nginx 对我来说看起来不错。

在您的 Go 代码中,当您创建路由器时,您可以使用 myapp 作为 PathPrefix,如下所示:

baseRouter := mux.NewRouter()
subRouter := baseRouter.PathPrefix("/myapp").Subrouter()
subRouter.HandleFunc("/something", routes.SomeHandler).Methods("GET")

或者干脆将 myapp 添加到路径中:baseRouter.HandleFunc("/myapp/something", routes.SomeHandler).Methods("GET")

【讨论】:

    【解决方案2】:

    您的 nginx 配置非常好。

    您提到的路径 (/myapp/something) 将显示 404,因为您尚未在您的路线中注册它。

    我建议,如果您希望使用同一个域托管多个应用程序,最好使用子域 (myapp1.mydomain.com) 而不是路径 (mydomain.com/myapp1)。

    对于每个子域,您可以通过仅更改 server_name 值并保持 nginx 服务器文件的其余部分相同来创建单独的 nginx 服务器块。

    然后,在使用中间件时,您可以过滤掉域并提供请求的资源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-07
      • 2017-08-16
      • 2017-07-17
      • 1970-01-01
      • 2021-01-27
      • 2020-08-19
      • 1970-01-01
      • 2020-06-29
      相关资源
      最近更新 更多