October 22, 2012

Deploy multiple Node applications on one web server in subdomains with Nginx

Earlier I wrote about deploying multiple Node applications on one web server in subfolders with Nginx.

Even though this approach is fully viable, you should not use it unless there are some really important reasons forcing you to go for it.

Given that the application is mounted to a subfolder, you should use relative URLs only in pages. Otherwise the application location must be configured in both Nginx and application itself. Use of relative URLs has a couple of major drawbacks:

  • If you want to move a page within hierarchy, you need to update its content. For example, you have a page that makes an AJAX call to ../getValue. Once you move your page one level up or down in the hierarchy, it does not work.
  • You need to solve a "trailing slash problem". For example, the page http://myhost/demo/pet-project/user-list must be also resolvable as http://myhost/demo/pet-project/user-list/. But if it refers a CSS file as ../css/user-list.css, the server will look for it at /opt/demo/pet-project/public/css/user-list.css and /opt/demo/pet-project/public/user-list/css/user-list.css correspondingly. It can be fixed by introducing the concept of canonical URLs and redirecting the client to the "proper" URL with or without trailing slash, depending on the chosen convention.

To minimize the maintenance complexity and avoid performance downgrade I decided to deploy Node applications in subdomains. With this approach I can freely use absolute URLs and thus easily shuffle my pages and have valid references without annoying redirects.

Nginx configuration for this setup is very similar to the one with subfolders and even a little bit more simple:

Finally you need to configure a DNS record for pet-project.myhost pointing to your server.


Unknown said...

Hi, would oyu mind sharing the nginx config for this? I had something similar in mind for my current problem.

Stevie said...

Sergey - thank you so much for posting your config. It worked perfectly for me on my EC2 server for separate node apps!