简体   繁体   English

nginx + nodejs配置

[英]nginx + nodejs configuration

I have a problem with my current nginx configuration. 我的当前nginx配置有问题。 What I am trying to do is: 我想要做的是:

  • For requests without any path, get the index.html (works) 对于没有任何路径的请求,获取index.html(有效)
  • Get existing files directly (works) 直接获取现有文件(有效)
  • If the requested file or path does not physically exist, proxy request to nodejs (404) 如果请求的文件或路径实际上不存在,则向nodejs发送代理请求(404)

I have tried several configurations found here on stackoverflow, but none of them fit my needs. 我在stackoverflow上尝试了几种配置,但它们都不符合我的需求。

Here is my current configuration: 这是我目前的配置:

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

I think I figured out what you were trying to do. 我想我弄明白你要做什么。 The proper way is to use try_files together with a named location. 正确的方法是将try_files与命名位置一起使用。

Try with the following configuration: 尝试使用以下配置:

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

Note: When you have an upstream defined you should use that in your proxy_ pass . 注意:如果定义了上游,则应在proxy_ pass使用该上游。 Also, when proxying, always add the X-Forwarded-For header. 此外,在代理时,始终添加X-Forwarded-For标头。

I was wondering that problem is in application path. 我想知道问题是在应用程序路径中。 Please find the following code excerpt from toontuts blog for full configuration of nginx with nodejs, you may find this link 请从toontuts博客中找到以下代码摘录,以获取有关nodejs的nginx的完整配置,您可以找到此链接

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM