【发布时间】: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 施展了它的黑魔法。