Rémi Becheras Rémi Becheras - 9 months ago 63
Node.js Question

Which is most efficient : serving static files directly by nginx or by node via nginx reverse proxy?

I already use

reverse proxy
to serve my
for example. Actually, I serve my assets in the node app, using

I read and read again that nginx is extremely efficient to serve static files.

The question is, what is the best ? Serving assets as I already do or configuring nginx to serve the static files itself directly ?

Or it is almost the same ?

Answer Source

The best way is to use nginx server to serve you static file and let you node.js server handle the dynamic content.

It is usually the most optimized solution to reduce the amount of requests on your node.js server that is slower to server static files than nginx for example :

The configuration to achieve that is very easy if you already set a reverse proxy for you nodejs app.

nd nginx configuration could be

   root /home/myapp;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location /public/ {
            alias /home/myapp/public/;

    location / {
            proxy_pass http://IPADRESSOFNODEJSSERVER:8080;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            #try_files $uri $uri/ =404;

Every request with /public/ at the first part of the url will be handled by nginx and every other request will be proxied to you nodejs app at your IPADRESSOFNODEJSSERVER:NODEJSPORT usually the IPADRESSOFNODEJSSERVER is the localhost

The doc section of express tell that http://expressjs.com/en/advanced/best-practice-performance.html#proxy

An even better option is to use a reverse proxy to serve static files; see Use a reverse proxy for more information.

Moreover nginx will let you easily define caching rules so for static assets that doesn't change it can speed up your app also with one line.

location /public/ {
            expires 10d;
            alias /home/myapp/public/;

You can find a lot of articles that compare the both methods on internet for example: http://blog.modulus.io/supercharge-your-nodejs-applications-with-nginx