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

时间:2018-08-15 12:35:08

标签: javascript html node.js nginx caching

我正在尝试从公共目录中提供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 {
        }
    } 

但是nginx服务器获取了所有对“ /”的请求,并尝试为我提供静态文件,因此我看不到来自节点的index.html。如何在“ /”路径上呈现index.html?

2 个答案:

答案 0 :(得分:0)

如果使用的是express,则只需配置express.static。文件:https://expressjs.com/en/starter/static-files.html

如果要从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 {
    }
} 

答案 1 :(得分:0)

您可以使用以下Nginx配置轻松解决此问题。

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

在您的快速应用中,.html文件使用/ public前缀访问这些静态文件。示例:“ http://sample.com/public/app.css