我已经设置了nixOS
来运行nginx
作为 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)
}
}
}
我的应用程序的 struct 是这样的.
├── 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.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
文件定向到同一位置是行不通的.