代理 nginx Express - 静态文件上的 404
proxying nginx Express - 404 on static files
当我从我的服务器 ip:port 浏览站点时,expressjs 应用程序的静态文件完美运行,但是当该应用程序从 nginx 提供服务时,静态文件给出 404 。这是我的 nginx 配置文件:
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;
}
...
}
}
当我从我的服务器 ip:port 浏览站点时,expressjs 应用程序的静态文件完美运行,但是当该应用程序从 nginx 提供服务时,静态文件给出 404 。这是我的 nginx 配置文件:
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;
}
...
}
}