Nginx为多个位置加载静态文件

Nginx load static files for multiple locations

本文关键字:加载 静态 文件 位置 Nginx      更新时间:2023-09-26

我在nginx .conf文件中有多个位置,像这样。

server {
    ...
    location /api/ {
            client_max_body_size 0;
            proxy_pass http://127.0.0.1:8000/api/;
            proxy_redirect off;
            proxy_read_timeout 5m;
            proxy_set_header Host $host;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X­Forwarded­For $proxy_add_x_forwarded_for;
    }
    ...
    location /cliente/ {
            proxy_pass http://127.0.0.1:4000/;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header HOST $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_redirect off;
    }
   location / {
            proxy_pass http://127.0.0.1:8000/;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header HOST $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_redirect off;
    }

在大多数情况下,这些位置是提供自己的静态文件和api rest的节点服务器。

在每个节点应用程序中加载静态文件使用html文件,并调用如下

/my-static-path-1/
/my-static-path-2/

问题:

当服务器尝试加载路径时,这是直接从/加载,而不是使用自己的子路径,导致404错误。

例子:

1) url http:/myip_sample.com/cliente调用提供html文件的nodejs应用程序,该文件需要加载像/my-static-path/js/sample.js这样的css脚本。

2)这个文件调用http:/myip_sample.com/my-static-path/js/sample.js代替http:/myip_sample.com/client /my-static-path/js/sample.js

我想在不改变任何东西的情况下做到这一点,只使用nginx配置文件。

提前感谢!

对每个资源文件夹的位置使用

location /my-static-path-1 {
        alias /location/to/my-static-path-1;
    }
location /my-static-path-2 {
        alias /location/to/my-static-path-2;
    }