使用子域上具有不同根文件夹的多个位置配置nginx

使用子域上具有不同根文件夹的多个位置配置nginx,nginx,webserver,Nginx,Webserver,我想把一个子域的根url和一个子域的目录提供给我服务器上的两个不同文件夹。这是一个简单的设置,我有,但不工作 server { index index.html index.htm; server_name test.example.com; location / { root /web/test.example.com/www; } location /static { root /web/test.

我想把一个子域的根url和一个子域的目录提供给我服务器上的两个不同文件夹。这是一个简单的设置,我有,但不工作

server {

    index index.html index.htm;
    server_name test.example.com;

    location / {
            root /web/test.example.com/www;
    }

    location /static {
            root /web/test.example.com/static;
    }
}
在本例中,转到
test.example.com/
会将索引文件放入
/web/test.example.com/www

location <lastPath> {
    root <FirstPath>;
}

转到
test.example.com/static
会将索引文件放入
/web/test.example.com/static
,您需要使用
别名
指令执行
位置/static

server {

  index index.html;
  server_name test.example.com;

  root /web/test.example.com/www;

  location /static/ {
    alias /web/test.example.com/static/;
  }

}
以下内容比我所能更好地解释了root和alias之间的区别:

请注意,乍一看它可能类似于root指令,但文档根不会更改,只更改用于请求的文件系统路径。请求的位置部分在请求Nginx问题中被删除

请注意,
root
alias
处理尾部斜杠的方式不同

server {

    index index.html index.htm;
    server_name test.example.com;

    location / {
        root /web/test.example.com/www;
    }

    location /static {
        root /web/test.example.com;
    }
}

位置指示系统是

您希望转发所有启动
/static
的请求,以及
/var/www/static
中的数据

所以一个简单的方法是将最后一个文件夹和完整路径分开,这意味着

完整路径:
/var/www/static

最后一个路径:
/static
和第一个路径:
/var/www

location <lastPath> {
    root <FirstPath>;
}
您的解决方案:

location /static {
    root /web/test.example.com;
}

一个更详细的例子

设置:您在
example.com
有一个网站,在
example.com/webapp

。。。
服务器{
听443ssl;
server_name example.com;
root/usr/share/nginx/html/website\u dir;
index.html index.htm;
尝试_文件$uri$uri//index.html;
地点/网络应用程序/{
别名/usr/share/nginx/html/webapp_dir/;
index.html index.htm;
尝试_文件$uri$uri//webapp/index.html;
}
}
...
我特意命名了
webapp\u dir
website\u dir
。如果您有匹配的名称和文件夹,则可以使用
root
指令

此设置工作正常,并使用Docker进行了测试


注意!!!小心割伤。完全按照示例中的方式放置。

他不需要
别名
。请阅读,而不是用户填写的社区维基。引号:当位置与指令值的最后一部分匹配时,最好使用root指令。这对我来说很有效,只是它缺少一个尾随斜杠。别名应为:alias/web/test.example.com/static/@VBart文档确实准确地说出了您引用的内容,但它们根本不能证明该指令是正确的——这似乎是一种任意的风格选择。你看到它背后的逻辑原因了吗?这是没有尾随的工作/在我的情况下。但最好的方法似乎是,我需要在“别名”行下使用“try_files$uri$uri/=404;”吗?问有什么不同吗?@woodd区别:
root/web/test.example.com
而不是
root/web/test.example.com/static。nginx将location指定的路径映射到diretory树,由于路径和源目录共享相同的名称,因此它与
root
一起工作。这帮助了我:让我意识到我需要重命名文件夹或设置符号链接才能正常工作。非常感谢,我就是这样失败的:)这看起来是对我想做什么的自由的一个相当严重的限制。我希望从物理文件路径中不包含该URI路径的目录中提供以特定路径开始的URI。使用此解决方案,我被迫将文档放在以“/static”结尾的磁盘路径下。我一点也不喜欢这个。我想要绝对和完全的自由,把文件放在我想要的任何地方。Szczepan Hołyszewski,那么也许你应该尝试构建自己的web服务器。这将给你绝对和完全的自由,把文件放在任何地方,你想。