您无需配置Nginx 和 Express即可提供静态文件。两者都有能力独立完成这项工作,但这取决于您选择。
对于这些示例,我假设您的问题中提供的文件结构相同。
在这两种配置中,都从/加载HTML文件:
<script src="/main.js"></script> <!-- loads from myapp/public/main.js -->
Express作为静态文件服务器,Nginx作为反向代理
快递应用
const express = require('express');const app = express();app.use(express.static('public')); // notice the absence of `__dirname`, explained later on// if the request URL doesn't match anything in the 'public' folder,// it will start searching here next.app.use(express.static('some_other_folder'));// from my testing, express will automatically locate index.html if// it is in a static folder. Declaring a route is not required.app.listen(8080);// GET / => index.html// GET /main.js => main.js快速提示 :不需要使用
__dirnamein
express.static()。引擎盖下(实际上,这是在这里第65行),快速使用本机的Node.js path.resolve()
。从文档:
path.resolve()方法将一系列路径或路径段解析为绝对路径。
使用
path.resolve(__dirname, 'public')实际上会 返回与相同
的结果
path.resolve('public')。我认为您的问题确实是在告诉Nginx提供静态文件并将相同的请求代理到Express。好,接下来我的答案。Nginx配置
server { listen 8081; # must be different port from Express server_name example.com; location / { # hand ALL requests back to express proxy_pass http://localhost:8080; }}Nginx作为静态文件服务器,Express作为API服务器
Nginx配置
server { listen 8081; server_name example.com; location / { root /path/to/website/public; index index.html; try_files $uri $uri/ @express; # instead of 404, proxy back to express using a named location block; # source: https://stackoverflow.com/a/15467555/8436941 } location @express { proxy_pass http://localhost:8080; }}快递应用
const express = require('express');const app = express();// actually, Nginx has already taken care of static files. You can still define other routes for API functions for example.app.get('/my/api', (req, res) => {});app.listen(8080);希望这可以帮助!



