简体   繁体   English

如何使用NGINX和Node.js提供静态文件(css,js,img)

[英]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: 我试图从我的公共目录中提供css,img和js静态文件(此目录中没有任何html),因此为此,我像这样配置了nginx服务器指令:

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. 但是nginx服务器获取了所有对“ /”的请求,并尝试为我提供静态文件,因此我看不到来自节点的index.html。 How to render my index.html on "/" route? 如何在“ /”路线上呈现我的index.html?

If you are using express, you only need to configure express.static. 如果使用express,则只需配置express.static。 Docs: https://expressjs.com/en/starter/static-files.html 文件: https//expressjs.com/en/starter/static-files.html

If you want to configure it from nginx add a layer to your path like this. 如果要从nginx配置它,请在路径中添加一个这样的图层。

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

You can solve this easily with the following Nginx config. 您可以使用以下Nginx配置轻松解决此问题。

Nginx Config Nginx配置

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. 在您的快速应用中,.html文件使用/ public前缀访问这些静态文件。 Example: ' http://sample.com/public/app.css ' 例如:“ http://sample.com/public/app.css

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM