2

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?

2 Answers 2

3

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'

Sign up to request clarification or add additional context in comments.

16 Comments

is this a best practice?
Yes. @Nastro. Because nginx is more powerful in caching than the node server. In fact, you don't need to have the public configuration in the express app. You can move it to the nginx. This reduces the burden for node app. Cheers.
Do upvote and mark as verified if this solves your problem. So that it will be helpful for others. @Nastro
What about try_files way. You can serve static files without the need to have a /public root path.
With try_files directive, nginx will try to find the requested resource within the static files and if failed finally it will pass it to the node server. But with my solution we are avoiding unnecessary searching of files by nginx @Clujio
|
0

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 {
    }
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.