我已经在使用 nginx
作为reverse proxy
为我服务node.js
网络应用程序 3000<->80
例如。实际上,我使用 express.static
在 Node 应用程序中提供我的 Assets 。中间件。
我读了又读,nginx 在处理静态文件方面非常高效。
问题是,什么是最好的?像我已经做的那样提供 Assets 或配置 nginx 以直接提供静态文件本身?
还是几乎一样?
最佳答案
最好的方法是使用 nginx 服务器为您提供静态文件,让您的 node.js 服务器处理动态内容。
它通常是最优化的解决方案,可以减少 node.js 服务器上的请求量,例如比 nginx 更慢的服务器静态文件:
如果您已经为您的 nodejs 应用程序设置了反向代理,那么实现这一目标的配置就非常容易。
nd nginx 配置可以是
root /home/myapp;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location /public/ {
alias /home/myapp/public/;
}
location / {
proxy_pass http://IPADRESSOFNODEJSSERVER:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
#try_files $uri $uri/ =404;
}
在 url 的第一部分带有/public/的每个请求都将由 nginx 处理,并且每个其他请求都将在 IPADRESSOFNODEJSSERVER:NODEJSPORT
代理到您的 nodejs 应用程序,通常是 IPADRESSOFNODEJSSERVER
是本地主机
express 的文档部分告诉我们http://expressjs.com/en/advanced/best-practice-performance.html#proxy
An even better option is to use a reverse proxy to serve static files; see Use a reverse proxy for more information.
此外,nginx 可以让您轻松定义缓存规则,因此对于不会更改的静态 Assets ,它也可以通过一行来加速您的应用。
location /public/ {
expires 10d;
alias /home/myapp/public/;
}
您可以在互联网上找到很多比较这两种方法的文章,例如: http://blog.modulus.io/supercharge-your-nodejs-applications-with-nginx
关于node.js - 哪个最有效 : serving static files directly by nginx or by node via nginx reverse proxy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36422462/