Thursday, January 5, 2012

Running Node.js Alongside Apache

I decided to set up Node.js on my Linux server running Apache.  Getting a Node.js server running was trivially simple, but I had a bit of trouble getting the mod_rewrite stuff correct to make it pretty (i.e. no port in the URL).  Basically I wanted to create a sub-directory on my site and route all the requests going there to my Node.js server, leaving everything else as-is.  So, http://kevnls.com/ and http://kevnls.com/etc/ would still be handled by Apache, but http://kevnls.com/node/ would be handed-off to Node.js.

Before I began, I already had Node.js serving up content at http://kevnls.com:8000.  I'm not going to address that part, because there are plenty of resources that can help you get to that point.

The first thing I needed to do was create a symlink to the directory where my Node.js server was running (/home/shared/node/).  In my case my CMS has a public/ folder where I can put stuff like 'whatever.txt' and it will resolve to http://kevnls.com/whatever.txt.  So, this is where I created a symlink.  At this point http://kevnls.com/node/ pointed to /home/shared/node/ in the filesystem.

Then in the /home/shared/node/ folder I created my .htaccess file with this mod_rewrite rule:

-----------------------------------------------------------------

Options +FollowSymLinks -Indexes -MultiViews

RewriteEngine on

RewriteRule ^(.*)$ http://kevnls.com:8000/$1 [P]

-----------------------------------------------------------------


Then I needed to get the proper modules running in Apache to handle what I wanted to do.  You can issue the following shell command and just type in the modules you want to enable:


a2enmod

In my case I needed 'proxy', 'proxy_http' and 'rewrite'.



After a quick Apache restart everything was working the way I wanted it.  Now on to the coding.

No comments: