Nginx try_files用于多个目录

时间:2017-06-22 03:13:39

标签: node.js nginx

我在/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表示app加载正常,但当然没有静态文件可访问。我有什么不对?

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;
}

1 个答案:

答案 0 :(得分:0)

首先,您应该告诉我们后端localhost:3000的作用:

  1. /static/public位置找不到文件时,它用作后备广告;
  2. 或者它用作HTTP API来处理具有某些URL,方法等的用户请求。
  3. 在这两种情况下,您都应该将配置拆分为两个不同的位置。

    在第一种情况下,您应该使用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;
    }