Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx.conf and Node.js setup scenario

Tags:

node.js

nginx

Today I've installed a NGINX server for a first time. It works very well but I'm facing a small problem with the configuration of server to work together with node.js.

I want to have the following logic in the nginx.conf.

  1. Directory listing to be disabled
  2. All static files(images, js, less and css) to be served from the NGINX
  3. All requests like http://hostname/remote_data/??/??/?????? to be routed to the node.js server
  4. All requests like http://hostname/??/??/?????? to be routed to the index.html, so not to reach the node.js

question marks are optional parameters :) It is possible to have from 0 to 7 parameters.

I apologize if this setup scenario is very easy to be done, but I'm fighting with it almost 3 hours and I'm stuck. Step 1 and 2 are ready - 10x to google.

Regards Dan

like image 893
Dan Avatar asked Jan 12 '12 21:01

Dan


2 Answers

You should check out this answer. From following the accepted answer there I got something like this:

upstream node_app {
    server localhost:8080;
}

server {

  listen 80;
  server_name FOO_HOSTNAME_GOES_HERE;

  root /the/root/to/foo/document/root;
  access_log /var/log/nginx/foo.access.log;
  error_page 404 /404.html;

  location /remote_data/ {

    # Proxy request to node:

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://node_app;
    proxy_redirect off;

    access_log /var/log/nginx/foo_nodeapp.access.log;

  }

  location / {
    try_files $uri $uri/index.html 404;
  }

}

Untested though.

like image 73
James Avatar answered Sep 28 '22 11:09

James


I've managed to make it work with the following conf:

server {
    root   /var/www;
    listen       80;
    server_name  _;


    location ~* /remote_data {
        # Proxy request to node:

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://node_app;
        proxy_redirect off;
        break;
    }       

    location / {
        index  index.html index.htm;

         location ~ \.(js|css|png|jpg|jpeg|gif|ico|html|less)$ {
             expires max;
             break;
        }

        rewrite ^/(.*)?$ /index.html?q=$1 last;
    }

    # serve static files directly
    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
        access_log        off;
        expires           30d;
    }
}
like image 42
Dan Avatar answered Sep 28 '22 12:09

Dan