如何配置位置块以始终在 nginx 中返回单个文件?

Hub*_*bro 15 configuration nginx

在我的应用程序中,我希望位置“/”返回静态 index.html 文件,我希望“/static”从文件夹中提供静态文件,并且我希望所有其他请求返回 404 NOT FOUND。稍后我会将所有其他请求重定向到 WSGI 服务器。

这是目前我的配置:

# Dev server.
server {
    listen 1337;
    charset UTF-8;

    location / {
        rewrite ^ static/index_debug.html break;
    }

    location /static {
        alias /home/tomas/projects/streamcore/static;
    }
}
Run Code Online (Sandbox Code Playgroud)

静态文件夹工作正常,但“/”返回 404 NOT FOUND。我也试过:

alias /home/tomas/projects/streamcore/static/index_debug.html;
Run Code Online (Sandbox Code Playgroud)

在位置块中,但返回 500 INTERNAL SERVER ERROR。似乎alias不喜欢单个文件。另外我试过:

try_files static/index_debug.html;
Run Code Online (Sandbox Code Playgroud)

但这会阻止服务器以错误“try_files 指令中的参数数量无效”开始。显然try_files实际上需要您尝试多个文件,这不是我正在寻找的行为。

所以我的问题是:如何配置位置块以始终返回静态文件?


编辑:我从其他答案中看到alias确实应该接受单个文件作为参数,所以我尝试了:

location = / {
    alias /home/tomas/projects/streamcore/static/index_debug.html;
}
Run Code Online (Sandbox Code Playgroud)

但我仍然只收到 500 INTERNAL SERVER ERROR。“/”请求的错误日志说:

[警报] 28112#0:*7“/home/tomas/projects/streamcore/static/index_debug.htmlindex.html”不是目录

为什么它试图打开“index_debug.htmlindex.html”?我没有在index任何地方使用该指令。

小智 11

刚刚测试了这个,它对我有用:

server {
    root /tmp/root;
    server {
        listen 8080;
        location /static {
            try_files $uri =404;
        }
        location / {
            rewrite ^ /static/index_debug.html break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该文件/tmp/root/static/index_debug.html当然存在:)

我可以点击任何 URL,我只得到静态页面。