在使用NGINX提供静态文件时如何用Node.js响应404?

时间:2016-04-16 11:01:04

标签: node.js nginx

我有一个在端口3000上运行的Node.js应用程序并使用NGINX作为代理。 NGINX也提供静态文件。启用网站的配置文件:

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),但是我希望在显示来自我的自定义404时保持URL指向不存在的路径节点应用

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用以下内容。

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选项中的示例。

相关问题