Hosting the Node API in nginx with a reverse proxy

August 20, 2014
close up laptop keyboard and screen with code

The Backbone application (coming in the next post in the series) will interact with the REST API using AJAX calls. Adding a reverse proxy allows those calls to work without browsers stopping the requests due to cross-site scripting (XSS) concerns and without setting up cross-origin resource sharing (CORS).

Using nginx

Nginx is used to setup a reverse proxy to the Node server. The API server (running in Node) listens to port 9090. Adding an nginx site configuration allows nginx to host a site that includes a reverse proxy to the Node server. Nginx listens to all incoming requests on port 9000. Any requests that start with /api are forwarded to the Node server running on port 9090.

This configuration will be modified when the Backbone application is added so that both the application and the API will run under port 9000 (thus removing the need to deal with XSS or CORS).

The Configuration

upstream api_node_js {
 server 127.0.0.1:9090;
}
server {
 listen 9000 default_server;
 listen [::]:9000 default_server ipv6only=on;
 root /usr/share/nginx/html;
 index index.html index.htm;
 # Make site accessible from https://localhost/
 server_name localhost;
 location / {
  # First attempt to serve request as file, then
  # as directory, then fall back to displaying a 404.
  try_files $uri $uri/ =404;
  # Uncomment to enable naxsi on this location
  # include /etc/nginx/naxsi.rules
 }
 location /api {
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $http_host;
  proxy_set_header X-NginX-Proxy true;
  rewrite ^/api/?(.*) /$1 break;
  proxy_pass https://api_node_js;
  proxy_redirect off;
 }
}

Adding the site to nginx

In order to make the site active in nginx, the configuration file needs to be placed into the sites-available directory and linked in the sites-enabled directory.

For a standard nginx configuration under Linux, shell scripts have been provided to initially configure the site and to redeploy the configuration when it changes.

Accessing the API

When complete, the API is available locally on both port 9090 and on port 9000.

You Might Also Like: