【问题标题】:How to serve static files (css, js, img) with NGINX and Node.js如何使用 NGINX 和 Node.js 提供静态文件(css、js、img)
【发布时间】:2019-01-22 08:04:53
【问题描述】:

我正在尝试从我的公共目录中提供 css、img 和 js 静态文件(我在此目录中没有任何 html),因此我配置了我的 nginx 服务器指令,如下所示:

server {
        listen       80;
        listen       [::]:80;
        server_name  my-site.com;
        root         /home/myuser/site/public;

        location / {
               proxy_pass "http://localhost:3000";
        }

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

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    } 

但是 nginx 服务器抓取所有对“/”的请求并尝试给我静态文件,所以我没有从节点看到我的 index.html。如何在“/”路由上渲染我的 index.html?

【问题讨论】:

    标签: javascript html node.js nginx caching


    【解决方案1】:

    如果使用express,只需要配置express.static。文档:https://expressjs.com/en/starter/static-files.html

    如果你想从 nginx 配置它,像这样在你的路径中添加一个层。

    server {
        listen       80;
        listen       [::]:80;
        server_name  my-site.com;
        root         /home/myuser/site/public;
    
        location / {
               try_files $uri $uri/ @nodejs;
        }
    
        location @nodejs {
               proxy_pass "http://localhost:3000";
        }
    
        error_page 404 /404.html;
            location = /40x.html {
        }
    
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    } 
    

    【讨论】:

      【解决方案2】:

      您可以使用以下 Nginx 配置轻松解决此问题。

      Nginx 配置

      server {
           listen       80;
           listen       [::]:80;
           server_name  my-site.com;
           location / {
              proxy_pass "http://localhost:3000";
           }
      
           location /public {
              root /PATH_TO_YOUR_NODE_APP_PUBLIC_DIRECTORY
              expires 30d;
           }
      }
      

      在您的快速应用程序 .html 文件中,使用 /public 前缀访问这些静态文件。示例:'http://sample.com/public/app.css'

      【讨论】:

      • 这是最佳做法吗?
      • 是的。 @纳斯特罗。因为 nginx 在缓存方面比节点服务器更强大。实际上,您不需要在 express 应用中进行公共配置。您可以将其移至 nginx。这减轻了节点应用程序的负担。干杯。
      • 如果这能解决您的问题,请点赞并标记为已验证。以便对其他人有所帮助。 @Nastro
      • try_files 方式怎么样。您可以提供静态文件,而无需 /public 根路径。
      • 使用 try_files 指令,nginx 将尝试在静态文件中查找请求的资源,如果最终失败,它会将其传递给节点服务器。但是通过我的解决方案,我们避免了 nginx @Clujio 对文件进行不必要的搜索
      猜你喜欢
      • 2014-01-12
      • 1970-01-01
      • 2014-07-09
      • 2015-10-19
      • 1970-01-01
      • 2017-05-10
      • 2021-09-03
      • 2015-07-30
      • 2017-01-06
      相关资源
      最近更新 更多