nginx + nodejs配置

Dan*_*iel 5 nginx node.js

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

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

我在stackoverflow上尝试了几种配置,但它们都不符合我的需求.

这是我目前的配置:

# 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;
}
}
Run Code Online (Sandbox Code Playgroud)

mek*_*all 12

我想我弄明白你要做什么.正确的方法是try_files与命名位置一起使用.

尝试使用以下配置:

# 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:当你有一个上游定义时,你应该在你的proxy_ pass.此外,在代理时,始终添加X-Forwarded-For标头.