nginx如何构建位置块中的文件路径?

时间:2013-10-04 18:22:44

标签: nginx

我正在尝试将GET /重写为/srv/app/static/index.html。我接近这几条指令:

root /srv/app/static;
location /static {
    alias /srv/app/static;
}
location = / {
    alias /srv/app/static/index.html;
}

所以,当我GET /static时,nginx会在/srv/app/static/index.html提供文件,我很高兴。

但是,当我GET /时,nginx返回404.检查日志,我看到它正在尝试访问文件/srv/app/static/index.htmlindex.html(原文如此)。为什么它会在index.html中给出的路径上额外添加alias

如果我将该指令更改为

location = / {
    index index.html;
    alias /srv/app/static/;
}

错误日志显示它正在尝试访问/srv/app/stati(原文如此,它会从c删除最终的/srv/app/static字符。这里发生了什么?

编辑:

我可以使用rewrite这样得到我想要的行为:

location = / {
    rewrite (.*) /static/index.html;
}

但是,我认为alias更具高效性和惯用性。

1 个答案:

答案 0 :(得分:0)

由于您已经设置了root,因此无需alias

只需

即可达到相同的效果
location = / {
    index index.html;
}

关于您的有趣问题,请查看documentation提到The location part of the request is dropped in the request Nginx issues.

基本上,这意味着用

location = / {
    alias /srv/app/static/index.html;
}

访问/实际上会尝试访问/srv/app/static/index.html 作为目录。我假设nginx将index.html附加为全局nginx.conf

的一部分

至于你在错误日志中获得/srv/app/stati,我并不确定会发生什么。也许你可以粘贴完整的日志条目?