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

问题描述 投票:0回答:1

我已经设置了一个

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

nginx
configuration.nix
部分的配置如下所示。

  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.css
htmx.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

另一个重要信息是,我想通过同一个反向代理以这种方式运行多个容器。因此,将 als

css
- 或
js
- 文件定向到同一位置将不起作用。

docker go nginx reverse-proxy nixos
1个回答
0
投票

请检查

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/
上提供服务,这应该使其易于维护。

© www.soinside.com 2019 - 2024. All rights reserved.