【问题标题】:Configure nginx to send back index.html for a 404配置 nginx 以返回 index.html 以获取 404
【发布时间】:2015-11-21 01:16:14
【问题描述】:

当我的 nginx(充当我的快速应用程序服务器的反向代理并提供静态资产)从它所代理的 API 返回 404 时,我正尝试将我的 index.html 发送回客户端。

这是我的 nginx 配置的相关服务器块:

server {
  listen  80;
  root    /var/www/dist;
  index   index.html index.htm;

  location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 1d;
  }

  location @proxy {
    proxy_set_header    Upgrade $http_upgrade;
    proxy_set_header    Connection "upgrade";
    proxy_set_header    Host $host;
    proxy_set_header    X-Real-IP $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header    X-NginX-Proxy true;

    proxy_http_version  1.1;
    proxy_redirect      off;
    proxy_pass          http://node-app;
    proxy_cache_bypass  $http_upgrade;
  }

  location / {
    try_files $uri $uri/ @proxy;
  }

  error_page 404 = /;

}

只是为了说明,这里的用例是我正在使用启用 HistoryLocation 的 React 路由器,所以现在如果我尝试刷新我的一条路由(如 example.com/signup),我会返回 404。

【问题讨论】:

    标签: node.js express nginx http-status-code-404 reverse-proxy


    【解决方案1】:

    当使用快速服务器(包括通过 nginx)时,在处理其他文件类型后,将 index.html 作为包罗万象的内容发回:

      app.get( /\.(js|css|png|jpg|svg)$/, function(req, res) {
        var uri = url.parse( req.url, true, false );
    
        sendFile( res, uri.pathname );
      } );
    
      //------------- return index.html for everything else so routing works
    
      app.get( '*', function(req, res) {
        sendFile( res, `${htmlPath}index.html` );
      } );
    

    如果只是直接使用nginx(不使用express),返回index.html 404错误:

      error_page 404 /index.html;
            location = /40x.html {
      }
    

    【讨论】:

      猜你喜欢
      • 2011-06-07
      • 2011-10-09
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多