【问题标题】:How to respond with 404 from Node.js when serving static files with NGINX?使用 NGINX 提供静态文件时,如何从 Node.js 响应 404?
【发布时间】:2016-04-16 11:01:03
【问题描述】:

我有一个 Node.js 应用程序在端口 3000 上运行并使用 NGINX 作为代理。 NGINX 也提供静态文件。 sites-enabled 中的 conf:

server {
    listen 80;
    server_name myapp.dev;

    location ~ ^/(img/|js/|css/|robots.txt|favicon.ico) {
        root /srv/nodejs/myapp/public;
        access_log off;
        expires max;
    }

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

目前一切正常。但是当请求一个不存在的静态文件(/css/doesntexist.css)时,我会得到一个默认的 NGINX 404 页面。

我知道可以将用户重定向到自定义 404 页面(例如 /404.html),但我希望在从我的 Node 应用程序显示自定义 404 时保持 URL 指向不存在的路径。

有什么想法吗?

【问题讨论】:

  • 您是否尝试过使用error_page
  • 感谢您的提示。我想我应该有 RTFM。

标签: node.js nginx


【解决方案1】:

得到它与以下工作。

location ~ ^/(img/|js/|css/|robots.txt|favicon.ico) {
    access_log off;
    expires max;
    error_page 404 = @not_found;
}

location @not_found {
    proxy_pass http://127.0.0.1:3000;
}

这是基于NGINX documentation for the error_page 选项中的一个示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-30
    • 2018-10-12
    • 2019-01-22
    • 2014-01-12
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多