使用路径/子文件夹重定向dockerized headless cms(directus)+反向代理(nginx)的问题

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

我有一个包含两个容器的 dockerized 设置:nginx 和后端 (=directus)。我希望 nginx 将

example.com/api/
的请求转发到我的后端容器,这几乎可以工作了。 nginx 配置文件如下所示

server {
    listen 80;
    server_name example.com;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /api/ {
        proxy_pass http://backend:8055/;
        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 $scheme;
    }
}

当我调用 example.com/api/ 时,我已经收到来自后端 (=directus) 的响应,它将我转发到 example.com/api/admin。到目前为止还好,但是管理页面的 html 中引用的脚本文件尚未加载。这些文件在 html 中用

<script type="module" crossorigin src="./assets/some-script-file.js"></script>
引用。浏览器尝试打开
http://example.com/admin/assets/some-script-file.js
而不是
http://example.com/api/admin/assets/some-script-file.js
。我不明白为什么网址的
/api/
部分会丢失。我该如何解决这个问题?

docker nginx reverse-proxy forwarding directus
1个回答
0
投票

我通过使用子域解决了这个问题,以便脚本 scr 标记中的所有相对 URL 都适用于该子域。感谢 Reddit 用户 tschloss 的提示。请注意,

http://backend:8055/
指的是我的后端(=directus)docker容器(container_name为“backend”并公开端口8055:8055)。另请注意,我必须调整 DNS 条目,以便为 api.example.com 添加 A 记录。

server {
    listen 80;
    server_name example.com;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://backend:8055/;
        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 $scheme;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.