Nginx 为 2 个不同的目录提供 2 个不同的 URL

Nginx Serve 2 Different Directories With 2 Different URLs

我想做的是使用 nginx 让它使用两个不同的 URL 在我的文件系统上的不同位置为两个不同的目录提供服务。因此,在我的文件系统上有两个目录 /path/to/dir1 和 /path/to/dir2 我希望我网站上的用户能够访问 mysite/d1 和 mysite/d2 并让每个 url 服务于 dir1 和目录 2 分别。这是我尝试过的:

server {

        listen       80;

        location /d1/ {
            root    /path/to/dir1;
            autoindex on;
        }

        location /d2/ {
            root   /path/to/dir2;
            autoindex on;
        }

    }

我有点困惑为什么这不起作用,因为当我使用配置时

server {

    listen       80;

    location / {
        root    /path/to/dir1;
        autoindex on;
    }

}

并导航到我的站点/我可以按预期访问 dir1

问题是当您使用 root 时追加请求 uri

  location /d1/ {
        root    /path/to/dir1;

这意味着您要搜索 /path/to/dir1/d1/ 中的文件。所以你需要的是一个别名,因为在别名的情况下 request_uri 只在声明的位置

之后使用
server {

        listen       80;

        location /d1/ {
            alias    /path/to/dir1;
            autoindex on;
        }

        location /d2/ {
            alias   /path/to/dir2;
            autoindex on;
        }

    }