javascript - 如何使用 NGINX 和 Node.js 提供静态文件(css、js、img)

标签 javascript html node.js nginx caching

我正在尝试从我的公共(public)目录提供 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 服务器会抓取所有对“/”的请求并尝试给我静态文件,所以我看不到来自 Node 的index.html。如何在“/”路线上渲染我的index.html?

最佳答案

您可以使用以下 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;
     }
}

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

关于javascript - 如何使用 NGINX 和 Node.js 提供静态文件(css、js、img),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51858801/

相关文章:

Javascript 宏 : implementing F# style forward pipe operator

javascript - 移动浏览器中javascript的图像加载显示功能

javascript - 在 saga : `while(true) take()` vs `while(take())` vs. `takeEvery()` 中监听 Action 的最佳方式

html - 使用 HTML5 音频播放 pls 文件

node.js - xml2json 安装错误找不到 Python 可执行文件,您可以设置 PYTHON 环境变量

javascript - 在javascript中用两种方式创建的运行函数

html - 如何将货币与 Handlebars 中的两倍进行比较

jquery - 如何让 jQuery.parseXML 在 node.js 中工作

node.js - NodeJS 函数之间传递变量

html - 希望内容以父为中心但 flex 包裹