【问题标题】:Nginx try_files for multiple directoriesNginx try_files 用于多个目录
【发布时间】:2017-06-22 03:13:39
【问题描述】:

我在 /var/www/vhosts/example.com/app/public 和 /var/www/vhosts/example.com/app/static 中有静态文件,我希望 nginx 签入。IE。 domain.com/photo.png 可以位于公共目录或静态目录中。

这是我的 nginx 配置,但使用 try_files 之类的,我的整个网站都会出现 nginx 500 内部服务器错误。没有这一行,我的 nodejs express 应用程序加载正常,但当然不能访问静态文件。我有什么问题?

location ~ / {
    root /var/www/vhosts/domain.com/app;
    try_files /public/$uri /static/$uri;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://localhost:3000;
}

【问题讨论】:

  • 您打算将其用于反向代理和提供文件吗?另外,如果你在linux上,请粘贴nginx -t的输出
  • 是的,我愿意。 nginx -t 的输出: nginx:配置文件/etc/nginx/nginx.conf 语法ok nginx:配置文件/etc/nginx/nginx.conf 测试成功

标签: node.js nginx


【解决方案1】:

首先你应该告诉我们后端localhost:3000 做了什么:

  1. 当在/static 和/public 位置都找不到文件时,它用作后备;
  2. 或者作为HTTP API来处理用户带有特定URL、方法等的请求。

在这两种情况下,您都应该将配置拆分到两个不同的位置。

在第一种情况下,您应该使用 try_files 和 proxy_pass 作为后备。

location / {
    root /var/www/vhosts/domain.com/app;
    try_files /public/$uri /static/$uri @fallback;
}

location @fallback {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://localhost:3000;
}

在第二种情况下,您应该按 URL 拆分位置,类似这样

location / {
    root /var/www/vhosts/domain.com/app;
    try_files /public/$uri /static/$uri @fallback;
}

location /api {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://localhost:3000;
}

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 2014-02-12
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    相关资源
    最近更新 更多