大网数据广告活动
服务器运维问答

How do I configure a location block to always return a single file in nginx?

· 52CE 我爱测

In my application I want the location "/" to return a static index.html file, I want "/static" to serve static files from a folder and I want all other requests to return 404 NOT FOUND. At a later point I'm going to redirect all …

问题原文

原帖链接 · Hubro · CC BY-SA 3.0

In my application I want the location "/" to return a static index.html file, I want "/static" to serve static files from a folder and I want all other requests to return 404 NOT FOUND. At a later point I'm going to redirect all other requests to a WSGI server.

This is currently my configuration:

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

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

    location /static {
        alias /home/tomas/projects/streamcore/static;
    }
}

The static folder is working perfectly, but "/" is returning 404 NOT FOUND. I have also tried:

alias /home/tomas/projects/streamcore/static/index_debug.html;

In the location block, but that returns 500 INTERNAL SERVER ERROR. It seems like alias doesn't like single files. Additionally I've tried:

try_files static/index_debug.html;

But that stops the server from starting with the error "invalid number of arguments in try_files directive". Apparently try_files actually requires you to try more than one file, which is not the behaviour I'm looking for.

So my question is: How so I configure a location block to always return a static file?


EDIT: I've seen from other answers that alias should indeed accept a single file as argument, so I tried:

location = / {
    alias /home/tomas/projects/streamcore/static/index_debug.html;
}

But I still only get 500 INTERNAL SERVER ERROR. The error log for the "/" request says:

[alert] 28112#0: *7 "/home/tomas/projects/streamcore/static/index_debug.htmlindex.html" is not a directory

Why is it trying to open "index_debug.htmlindex.html"? I'm not using the index directive anywhere.

已采纳解答

原帖链接 · chrskly · CC BY-SA 3.0

Just tested this and it works for me:

server {
    root /tmp/root;
    server {
        listen 8080;
        location /static {
            try_files $uri =404;
        }
        location / {
            rewrite ^ /static/index_debug.html break;
        }
    }
}

The file /tmp/root/static/index_debug.html exists of course :)

I can hit any URL and I just get the static page.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2013-02-06)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。