Nginx + Node.js配置 [英] nginx + nodejs configuration

查看:127
本文介绍了Nginx + Node.js配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的nginx配置有问题.我想做的是:

I have a problem with my current nginx configuration. What I am trying to do is:

  • 对于没有任何路径的请求,请获取index.html(有效)
  • 直接获取现有文件(有效)
  • 如果所请求的文件或路径实际上不存在,请向nodejs代理请求(404)

我已经尝试了在stackoverflow上找到的几种配置,但是都不符合我的需求.

I have tried several configurations found here on stackoverflow, but none of them fit my needs.

这是我当前的配置:

# IP which nodejs is running on
upstream app_x {
    server 127.0.0.1:3000;
}

# nginx server instance
server {
listen 80;
server_name x.x.x.x;
#access_log /var/log/nginx/x.log;

root /var/www/x/public;

location / {
    root /var/www/x/public;
    index index.html index.htm index.php;
}

location ^/(.*)$ {
    if (-f $request_filename) {
        break;
    }
    proxy_set_header Host $http_host;
    proxy_pass http://127.0.0.1:3000;
}
}

推荐答案

我想我已经弄清楚了您要做什么.正确的方法是将 try_files 与命名位置一起使用.

I think I figured out what you were trying to do. The proper way is to use try_files together with a named location.

尝试以下配置:

# IP which nodejs is running on
upstream app_x {
    server 127.0.0.1:3000;
}

# nginx server instance
server {
    listen 80;
    server_name x.x.x.x;
    #access_log /var/log/nginx/x.log;

    location / {
        root /var/www/x/public;
        index index.html index.htm index.php;
        try_files $uri $uri/ @node;
    }

    location @node {
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://app_x;
    }
}

注意:在定义上游时,应在proxy_ pass中使用它.另外,代理时,请始终添加 X-Forwarded-For 标头.

Note: When you have an upstream defined you should use that in your proxy_ pass. Also, when proxying, always add the X-Forwarded-For header.

这篇关于Nginx + Node.js配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆