为什么 nginx 不能为不同位置的站点提供服务?

Why nginx not able to serve sites in different locations?

我想使用 nginx 托管一些位于我电脑上不同路径的静态 html,下面是我的配置:

server {
    listen       8080;
    server_name  localhost;


    location /chatserver {
        root /Users/xxxx/gitrepo/chatserver/public;
        index index.html;
    }

    location /test {
        root /Users/xxxx/test/test_site;
        index index.html;
    }

文件结构为:

Users
  |-xxxx
    |-gitrepo
    |  |-chatserver
    |       |-public
    |          |- index.html
    |-test
       |-test_site
            |- index.html 

但是当我访问:http://localhost:8080/chatserverhttp://localhost:8080/test 时,nginx 总是响应 404 Not Found

如果我访问:http://localhost:8080/,nginx 将 return 默认的 nginx 欢迎页面。

为什么我的配置不起作用?

我认为你应该使用 alias 而不是 root

在您的示例中,URL /chatserver/index.html 将搜索 /Users/xxxx/gitrepo/chatserver/public/chatserver/index.html(请注意 public 之后的 "undesired" chatserver!)。检查您的 nginx 的日志文件!

参见 documentation of root and documentation of alias