【问题标题】:nginx + nodejs configurationnginx + nodejs 配置
【发布时间】:2013-12-21 04:56:02
【问题描述】:

我当前的 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;
}
}

【问题讨论】:

  • 只需删除if (-f $request_filename) 语句和中断?我真的不知道什么有效,什么无效,以及您的需求是什么。
  • 您没有为index.html 提供节点服务有什么原因吗?这会让事情变得更容易。
  • 我不使用 nodejs 提供 index.html 的原因是,它是静态 html。该项目是一个 ajax 驱动的应用程序,我试图用 nodejs 只提供 json。
  • 上游不使用有什么用?

标签: node.js nginx


【解决方案1】:

我想我知道你想做什么了。正确的方法是使用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;
    }
}

注意:当您定义了上游时,您应该在 proxy_ pass 中使用它。此外,代理时,请始终添加 X-Forwarded-For 标头。

【讨论】:

  • 非常感谢!我忘记先定义“根”指令。包含最后带有 $uri 的整个路径(不正确:/var/www/x/public/$uri)。
【解决方案2】:

我想知道问题出在应用程序路径中。请从 tontuts 博客中找到以下代码摘录,以使用 nodejs 完整配置 nginx,您可以找到 link

upstream subdomain.your_domain.com {
  server 127.0.0.1:3000;
}
 
server {
  listen 0.0.0.0:80;
  server_name subdomain.your_domain.com;
  access_log /var/log/nginx/subdomain.your_domain.access.log;
  error_log /var/log/nginx/subdomain.your_domain.error.log debug;
 
  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
 
    proxy_pass http://subdomain.your_domain.com;
    proxy_redirect off;
  }
}

【讨论】:

    猜你喜欢
    • 2015-06-10
    • 2017-06-08
    • 2018-05-18
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2017-01-17
    • 2016-11-28
    相关资源
    最近更新 更多