在nestjs中,如果使用 app.useStaticAssets
来定义静态资源路径和访问路径时,原来的Nginx接口代理会出现访问资源文件404,当然也可能不会出现,如果出现了继续看下面。
main.ts
// 静态资源
app.useStaticAssets(join(__dirname, '../uploads'), {
prefix: '/uploads',
});
只需要在Nginx中再添加一个转发就可以:
# 在上面添加这块代码就可以,其中的uploads,根据你useStaticAssets中设置的路径来
location ^~ /uploads/ {
proxy_set_header Host $host;
proxy_pass http://127.0.0.1:3000;
}
# 这块是nestjs服务转发
location / {
proxy_pass http://127.0.0.1:3000/;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
add_header X-Cache $upstream_cache_status;
proxy_set_header X-Host $host:$server_port;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 30s;
proxy_read_timeout 86400s;
proxy_send_timeout 30s;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
# 也可能是这块规则导致访问404,但这块我们不动它
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
error_log /dev/null;
access_log /dev/null;
}