关键代码
宿主机nginx配置
> worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://localhost:8072/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
gzip_static on;
gzip_proxied any;
}
location /static/ {
proxy_pass http://localhost:8072/static/;
proxy_set_header Host $host;
}
}
}
docker容器中nginx配置
map $http_host $request_port {
default 80;
"~^[^\:]+:(?<p>\d+)$" $p;
}
gzip on;
gzip_disable "msie6";
gzip_comp_level 6;
gzip_vary on;
gzip_proxied any;
gzip_buffers 16 8k;
gzip_min_length 256;
gzip_static on;
gzip_types
text/plain
text/css
application/json
application/javascript
text/xml
application/xml
application/xml+rss
text/javascript
image/svg+xml;
server {
listen 80 default_server;
resolver 127.0.0.11 valid=30s;
charset utf-8;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
打包的静态资源配置
compression({
verbose: true,
disable: false,
// 选择要压缩的文件类型
filter: /\.(js|mjs|json|css|svg)$/,
// 压缩算法,可选 'gzip' 或 'brotliCompress'
algorithm: 'gzip',
// 生成的压缩文件扩展名
ext: '.gz',
// 是否删除源文件,默认为 false
deleteOriginFile: true,
}),
问题描述
直接访问http://localhost:8072/#/ 可以正常访问到所有资源且都是经过压缩的gz,携带的响应头有content-encoding:gzip
但是如果从 http://localhost:80 即经过宿主机的nginx代理访问,压缩过的资源都会报404,其中一开始的html文件并没有经过压缩正常接收。携带的响应头都没有content-encoding:gzip
如果去掉 deleteOriginFile: true,和gzip_static on;不论是80还是8072都可以访问到压缩的资源,但是代价是牺牲大量的空间去存储源文件,所以仍然不是好的解决方案。