Nginx在nixOS上的反向代理,在尝试加载css/js时返回404错误。

3
我已经设置了一个nixOS来运行一个nginx作为docker容器的反向代理。在docker容器中运行一个golang服务器,它通过一个函数处理/并从static和js两个文件夹返回文件。它运行在8181端口上。代码如下:
func main() {
        static := http.FileServer(http.Dir("static"))
        js := http.FileServer(http.Dir("js"))
        http.Handle("/static/", http.StripPrefix("/static/", static))
        http.Handle("/js/", http.StripPrefix("/js/", js))
        // Register function to "/"
        http.HandleFunc("/", indexHandler)
        fmt.Println("Server is starting...")
        err := http.ListenAndServe("0.0.0.0:8181", nil)
        if err != nil {
                log.Fatal("cannot listen and server", err)
        }
        
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
        wd, err := os.Getwd()
        var static = filepath.Join(wd, "static")
        var index = filepath.Join(static, "index.html")
        if err != nil {
                log.Fatal("cannot get working directory", err)
        }

        // Check if the request is an OPTIONS preflight request
        if r.Method == "OPTIONS" {
                // Respond with status OK to preflight requests
                w.WriteHeader(http.StatusOK)
                return
        }

        // POST-Request
        if r.Method == http.MethodPost {
              // do something
        } else {
                // Loading the index.html without any data
                tmpl, err := template.ParseFiles(index)
                err = tmpl.Execute(w, nil) // write response to w
                if err != nil {
                        http.Error(w, err.Error(), http.StatusInternalServerError)
                        log.Fatal("problem with parsing the index template ", err)
                }

        }
}

我的应用程序的结构看起来像这样。
├── web
│   ├── Dockerfile
│   ├── go.mod
│   ├── server.go
│   └── static
│   │   ├── index.html
│   │   ├── style.css
│   │   └── table.html
│   └── js
│       └── htmx.min.js

configuration.nix中,nginx部分的配置如下。
  services.nginx = {
    enable = true;
    recommendedGzipSettings = true;
    recommendedOptimisation = true;
    recommendedProxySettings = true;
    recommendedTlsSettings = true;
    virtualHosts."myapp" = {
      sslCertificate = "/etc/ssl/nginx/ssl.cert";
      sslCertificateKey = "/etc/ssl/nginx/ssl.key";
      sslTrustedCertificate = "/etc/ssl/nginx/ssl.chain";
      forceSSL = true; # Redirect HTTP to HTTPS
      locations = {
        "/myapp" = { proxyPass = "http://localhost:8181/"; };
      };
      extraConfig = ''
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      '';
    };

  };

当我访问URL https://server/myapp 时,index.html会加载,但是style.csshtmx.min.js会返回404错误。
当使用端口8181而不是URL(http://server:8181)来访问容器时,一切都正常加载。
我希望nginx能将加载CSS和JS的请求重定向到容器。
编辑: 确切的错误是:GET https://server.name/static/style.css net::ERR_ABORTED 404,尽管我正在访问https://server.name/myapp
另一个重要信息是,我希望在同一个反向代理上以这种方式运行多个容器。因此,将CSS或JS文件指向相同位置的方法不起作用。
1个回答

2
请检查 index.html 文件中的 css/js 引用。很有可能你是使用绝对路径进行引用,就像这样:
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="/static/style.css" />
    <script src="/js/htmx.min.js"></script>
  </head>
</html>

一个快速的解决方法是用相对路径替换它们:
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="./static/style.css" />
    <script src="./js/htmx.min.js"></script>
  </head>
</html>

这种方法容易出错。一个更好的方法是修改应用程序以在/myapp上提供内容:

http.Handle("/myapp/static/", http.StripPrefix("/myapp/static/", static))
http.Handle("/myapp/js/", http.StripPrefix("/myapp/js/", js))
http.HandleFunc("/myapp/", indexHandler)

并修改index.html文件中的引用路径:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="/myapp/static/style.css" />
    <script src="/myapp/js/htmx.min.js"></script>
  </head>
</html>

然后修改nginx配置:
locations = {
  "/myapp/" = { proxyPass = "http://localhost:8181/myapp/"; };
};

使用这种方法,无论是否使用反向代理,Web 应用程序都将始终在 URI /myapp/ 上提供服务,这样就很容易进行维护。

1
将链接替换为相对路径并没有起作用。但是通过/myapp来提供所有内容对我来说是有效的。 - undefined
替换链接为相对路径没有起作用,这很奇怪。你在页面中添加了<base>元素吗?如果是的话,请将其移除然后再试一次。 - undefined
我在我的页面上没有放置<base>元素。 - undefined
感谢您的反馈!但我不知道为什么相对路径的方法不起作用。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接