start blog post

Running Apache and Node.JS Together

Node.JS is a fantastic server-side JavaScript solution by Ryan Dahl. One of its common examples is how easy it is to build an asynchronous HTTP web server. The problem with integrating Node into most real-world shared hosts is the host already has a web server listening on port 80 — probably Apache — and it's already serving your existing content.

Yes, your Node.JS server can use another port, but then you have to point people to something like instead of This makes transitioning to Node.JS feel a little less "real".

I'm going to show you how to transparently pass individual paths to Node.JS, without changing either your URLs or the way your existing content is served.

     * This is our Node.JS code, running server-side.
    var sys = require('sys'),
        http = require('http'),
        port = 8000; // TODO: set your actual port here
    http.createServer(function(request, response) {
        response.writeHead(200, {
            'Content-Type': 'text/html'
         * Here you can route or process the page based on request.url,
         * or you may want to use a module such as node-router.
    sys.puts('Server listening on port ' + port);

So far, so good. Run node http.js & (or whatever you called the above file) and your server should be up and running. The "&" at the end runs node in the background. Now for some easy .htaccess magic:

    # This is the .htaccess file in our document root.
    Options +FollowSymLinks -Indexes -MultiViews
    <IfModule mod_rewrite.c>
        RewriteEngine on
        # Simple URL redirect:
        RewriteRule ^test.html$ [P]
        # More complicated (the user sees only "benchmark.html" in their address bar)
        RewriteRule ^benchmark.html$ [P]
        # Redirect a whole subdirectory:
        RewriteRule ^node/(.+)$1 [P]

Request.url is basically equivalent to PHP's $_SERVER['REQUEST_URI'], meaning if you visit given the above code, Node.JS will provide "/testing/someFile.html" as request.url. Query strings are also included.

The amount of control this gives you allows you to phase in support for Node.JS as quickly or as slowly as you like, and from your visitors' point of view nothing changes. Anything you don't explicitly pass to Node will be handled by Apache (or your current web server).

Do you already use Node.JS alongside an existing web server? What projects are you running on Node, or what do you plan to run?

var tags = [, ];

  • share this post:
  • email a friend
  • float this post
  • digg this post
  • share on stumbleupon
  • submit to technorati
  • tweet this post

end blog post