Nastro
Nastro

Reputation: 1769

How to serve static files (css, js, img) with NGINX and Node.js

I'm trying to serve css, img and js static files from my public directory (I don't have any html in this directory), so for that I configured my nginx server directive like this:

server {
        listen       80;
        listen       [::]:80;
        server_name  my-site.com;
        root         /home/myuser/site/public;

        location / {
               proxy_pass "http://localhost:3000";
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    } 

But nginx server grabs all requests for "/" and tries to give me static files, so I don't see my index.html from node. How to render my index.html on "/" route?

Upvotes: 2

Views: 3913

Answers (2)

Bharathvaj Ganesan
Bharathvaj Ganesan

Reputation: 3184

You can solve this easily with the following Nginx config.

Nginx Config

server {
     listen       80;
     listen       [::]:80;
     server_name  my-site.com;
     location / {
        proxy_pass "http://localhost:3000";
     }

     location /public {
        root /PATH_TO_YOUR_NODE_APP_PUBLIC_DIRECTORY
        expires 30d;
     }
}

In your express app .html files access these static files with /public prefix. Example: 'http://sample.com/public/app.css'

Upvotes: 2

Clujio
Clujio

Reputation: 352

If you are using express, you only need to configure express.static. Docs: https://expressjs.com/en/starter/static-files.html

If you want to configure it from nginx add a layer to your path like this.

server {
    listen       80;
    listen       [::]:80;
    server_name  my-site.com;
    root         /home/myuser/site/public;

    location / {
           try_files $uri $uri/ @nodejs;
    }

    location @nodejs {
           proxy_pass "http://localhost:3000";
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
} 

Upvotes: 0

Related Questions