nginx作为一个具有高性能的http、https、反向代理web做事器,非常适宜托管静态资源文件。
常日我们利用Express框架来搭建一个nodejs web运用,这是一个非常不错的选择。现在我们通过一些例子来磋商本日的问题。
express 创建运用 基本实例
import express from "express";const app = express();// ... app.use、路由(app.get、app.post) 等。// app.use(express.static("assets"));app.get('/', (req, res) => { res.send('Hello World!')})app.listen(80, () => { console.log(`port:${port}`)})

app.use(express.static("assets"));// http://localhost:8080/img/logo.png// http://localhost:8080/css/index.css
app.use("/static", express.static("assets", { setHeaders }));// http://localhost:8080/static/img/logo.png// http://localhost:8080/static/css/index.css
比如说在多租户架构下,一个nodejs运用同时绑定N个站点。
举例:
多租户
// typescript 代码实例sendFile(req: core.Request, res: core.Response, host_code:string) { const filePath = `./sites/${host_code}${decodeURIComponent(req.path)}`; res.sendFile(filePath, { root: path.resolve(".") }, (err) => { if (err) { // ... } });}
在实际运用过程中,当访问量较大时,体验不是很完美。这个时候nginx登场了,完美的办理了干系问题,以是合理利用不同工具,争取做到尽善尽美,是乃毕生之所追求。
nginx 代理nodejs,并直接托管静态资源不走Nodejs
server{ listen 80; server_name video.prvt.cool; location / { # ... 其它配置 proxy_pass http://127.0.0.1:9010; } location /css { alias d://sites/web0015/assets/; }}server{ listen 80; server_name music.prvt.cool; location / { # ... 其它配置 proxy_pass http://127.0.0.1:9010; } location /css { alias d://sites/web0017/assets/; }}server{ listen 80; server_name prvt.cool www.prvt.cool; location / { # ... 其它配置 proxy_pass http://127.0.0.1:9010; } location /css { alias d://sites/web0016/assets/; }}
当您运行多个nodejs运用程序时,您希望他们都利用80端口时,这时候利用NGINX来代理,将会是一个完美的选择。
人人为我,我为大家,欢迎您的浏览,我们一起加油吧。