当我从服务器ip:port浏览站点时,expressjs应用程序的静态文件可以正常工作,但是当该应用程序从Nginx提供服务时,静态文件会显示404.这是我的Nginx conf:
upstream project {
server localhost:6546;
}
server {
listen 80;
server_name example.com;
access_log /var/log/Nginx/example.com_access.log;
error_log /var/log/Nginx/example.com_error.log;
location / {
proxy_pass http://project/;
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;
}
location ~* \.(css|js|gif|jpe?g|png)${
expires 168h;
}
这是我的expressjs静态代码:
app.enable('trust proxy');
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(__dirname + '/public'));
app.set('view engine','ejs');
if (app.get('env') === 'production') {
app.set('view cache',true);
}
最佳答案
尽管express.js通过某些连接中间件内置了静态文件处理功能,但您绝对不要使用它. Nginx可以更好地处理静态文件,并可以防止对非动态内容的请求阻塞节点进程.这是执行此操作的示例:
http {
...
server {
...
location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) {
root /home/ubuntu/expressapp/public;
access_log off;
expires max;
}
...
}
}