Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx + nodejs configuration

Tags:

node.js

nginx

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

  • For requests without any path, get the index.html (works)
  • Get existing files directly (works)
  • If the requested file or path does not physically exist, proxy request to nodejs (404)

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

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;
}
}
like image 716
Daniel Avatar asked Dec 21 '13 04:12

Daniel


2 Answers

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 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. Also, when proxying, always add the X-Forwarded-For header.

like image 158
mekwall Avatar answered Oct 03 '22 16:10

mekwall


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

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;
  }
}
like image 43
user3428046 Avatar answered Oct 03 '22 15:10

user3428046