应用程序在nginx反向代理上重定向错误。

huangapple go评论92阅读模式
英文:

Application on nginx reverse proxy redirects wrong

问题

问题:如何在我的应用程序内部(在nginx反向代理后运行)将重定向从应用程序的根目录改为服务器的根目录?

解决方案:您可以在应用程序中使用相对路径进行重定向,而不是绝对路径。在您的示例中,将重定向语句更改为以下内容:

func foo(w http.ResponseWriter, r *http.Request) {
  http.Redirect(w, r, "/", http.StatusFound)
}

这将使重定向指向应用程序的根目录,而不是服务器的根目录。

英文:

I am running an nginx (0.7.67) as a reverse proxy and a golang application. The nginx server is configured as follows:

...
location /bar/ {
  proxy_pass http://localhost:8088/;
  proxy_redirect off;
  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_set_header  X-Forwarded-Proto  https;
}
...

The source of my golang application (it doesn't make sense, only an example):

func root(w http.ResponseWriter, r *http.Request) {
  fmt.Fprint(w, "You reached root")
}

func foo(w http.ResponseWriter, r *http.Request) {
  http.Redirect(w, r, "/", http.StatusFound)
}

func main() {
  http.HandleFunc("/", root)
  http.HandleFunc("/foo", foo)
  http.ListenAndServe("localhost:8088", nil)
}

Problem: When I direct my browser to the URL of my application (https://domain.tld/bar/) I can see the text "You reached root". However, if I try to open https://domain.tld/bar/foo, I get redirected to https://domain.tld instead of https://domain.tld/bar. It seems that my application is redirecting to the root of the nginx server and not the application.

Question: How can I redirect from the inside of my application (running behind an nginx reverse proxy) to the root of my application, instead of the root of the server?

答案1

得分: 2

这是一个无法自动解决的问题,无论是哪种语言,甚至是PHP。像WordPress这样的应用程序会有一个设置来指定根目录。有些应用程序需要一个完整的URL(https://domain.tld/bar),或者只需要一个路径(/bar)。

无论哪种方式,你都需要创建一个设置,然后手动配置所有的重定向都基于该设置。你可以创建自己的重定向函数,这样每次重定向时就不需要实现它。

英文:

This is a problem that cannot be solved automatically in any language, even PHP. What applications such as wordpress do is have a setting to specify the root. Some applications require a full url (https://domain.tld/bar) or can just have a path (/bar).

Either way, you need to create a setting and then manually configure all redirects to be based from there. You can create your own redirect function so you don't need to implement it each time you do a redirect.

huangapple
  • 本文由 发表于 2013年2月6日 02:26:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/14714310.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定