Using Nginx to server static files instead of Node.js

With NodeJS becoming popular with standard websites, a performance impact which is often overlooked is using the built-in NodeJS server to serve static files.  While NodeJS is self-hosting, it’s wise to place an Nginx server in-front and proxy requests. You can then use this to serve your static files allowing your node process to only handle dynamic content.

An example of how to configure Nginx to serve static files on a separate domain:

server {
        listen   80;
        server_name  static.domain.com;

        access_log  /var/log/nginx/static_domain_access.log;
        #access_log off; #Save disk space and IO

       location ~* ^.+.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
       {
            root  /website/path/to/static/files/in/node/repository/public/;
       }
}

If your using Nginx as a node proxy then specifying multiple location configurations (untested) in your main domain config will mean you can make the infrastructure change without affecting the code.

       location ~* ^/images/.+.(jpg|jpeg|gif|png|ico|css)$
       {
            root  /website/path/to/static/files/in/node/repository/public/images/;
       }
        location ~* ^/stylesheets/.+.(css)$
       {
            root  /website/path/to/static/files/in/node/repository/public/stylesheets/;
       }
       location ~* ^/javascript/.+.(js)$
       {
            root  /website/path/to/static/files/in/node/repository/public/javascript/;
       }

More details at http://wiki.nginx.org/NginxHttpCoreModule#location

Few other points not covered:
1) Consider using a CDN and a separate domain to improve performance. The separate domain means cookies won’t be sent and allowing browsers to download artifacts in parallel which both improve performance. As an example, Facebook has www.fbcdn.com with Google using www.gstatic.com
2) Consider GZipping contents
3) Consider your caching strategy

Leave a Reply

Your email address will not be published. Required fields are marked *