Nginx 服务 angular 个静态文件

Nginx serving angular static files

我正在配置更改在 nginx 中部署的 angular 项目的部署。默认文件托管在 /usr/share/nginx/html,当我从本地主机访问时可以使用。但是,我想在 URL 处定义 /dev 或 /prod,看起来像:localhost/dev 或 localhost/prod 但是当我更改 nginx 配置时它不起作用,因为它保持在 /usr/share/nginx/html/dev

寻找文件

我如何重写 URL 以指向静态文件所在的 /usr/share/nginx/html?

当前 nginx 位置配置:

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

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

错误:

2021/09/14 01:43:34 [error] 75#75: *7 "/usr/share/nginx/html/dev/index.html" is not found (2: No such file or directory), client: 172.18.0.1, server: localhost, request: "GET /dev/ HTTP/1.1", host: "localhost:4201"

我试过更改配置,但我遇到了一个被禁止的问题 配置:

    location /dev/ {
        #root   /usr/share/nginx/html;
        #index  index.html index.htm;
        alias /usr/share/nginx/html;
        try_files $uri $uri/ /index.html;
    }

错误:

 2021/09/14 02:11:45 [error] 92#92: *10 directory index of "/usr/share/nginx/html" is forbidden, client: 172.18.0.1, server: localhost, request: "GET /dev/ HTTP/1.1", host: "localhost:4201"

我在网上找到了一些资源,这些资源帮助我排除故障并成功启动。

  1. 如果你面对的是nginx HTML 是禁止的 --> https://programmer.group/directory-index-of-usr-share-nginx-html-is-forbidden.html

  2. 对于别名,我们需要在后面添加/

location /prod/ {
    alias  /usr/share/nginx/html/dev/;
    try_files $uri $uri/ /index.html;
}