http - nginx 反向代理上的应用程序重定向错误

标签 http redirect nginx go reverse-proxy

我正在运行 nginx (0.7.67) 作为反向代理和 golang 应用程序。 nginx服务器配置如下:

...
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;
}
...

我的golang应用程序的来源(没有意义,只是一个例子):

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)
}

问题:当我将浏览器定向到应用程序的 URL ( https://domain.tld/bar/ ) 时,我可以看到文本“您已达到 root 权限”。但是,如果我尝试打开 https://domain.tld/bar/foo ,我被重定向到 https://domain.tld而不是https://domain.tld/bar 。看来我的应用程序正在重定向到 nginx 服务器的根目录,而不是应用程序。

问题:如何从应用程序内部(在 nginx 反向代理后面运行)重定向到应用程序的根目录,而不是服务器的根目录?

最佳答案

这是任何语言都无法自动解决的问题,即使是 PHP。 wordpress 等应用程序所做的就是有一个指定根目录的设置。某些应用程序需要完整的 url ( https://domain.tld/bar ),或者只需要一个路径 (/bar)。

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

关于http - nginx 反向代理上的应用程序重定向错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14714310/

相关文章:

ubuntu - Nginx 重定向 301 非 ssl www 到 ssl www 无法正常工作

php - 尝试使用 PHP header ("Location: ") 函数进行重定向

javascript - 如何从 Firefox 扩展发出 HTTP 请求

http - 哪个 HTTP 状态代码用于未提供的必需参数?

asp.net - 如何在 ASP.Net MVC 中执行 301 永久重定向路由

nginx - 如何在 nginx 上安装模块?

nginx - pgadmin4 无法在 nginx 后面的特定位置工作

nginx - ServiceStack Docker 架构

安卓8 : Cleartext HTTP traffic not permitted

javascript - 使用 Node JS 在 Node JS 上进行 HTTP 请求回调