wuyuedefeng / blogs

博客文章在issue中
5 stars 0 forks source link

nginx常用配置集锦 #149

Open wuyuedefeng opened 1 year ago

wuyuedefeng commented 1 year ago

文件过期/缓存

location ^~ /static/ {
  gzip_static on;
  expires max;
  add_header Cache-Control public;
}
# 缓存后缀文件
location ~* \.(css|js|gif|jpe?g|png)$ {
  gzip_static on;
  expires 100d;
  access_log off;
  add_header Pragma public;
  add_header Cache-Control "public";
}
# 不缓存htm, html
location ~ .*\.(htm|html)$ {
  # add_header Cache-Control no-cache;
  add_header Cache-Control "no-cache, no-store";
  expires -1;
}

根据路径转发到别的域名

# /file?key=111 =>  http://portal.zezeping.com/api/111
location = /file/getFile {
   resolver 8.8.8.8;
   proxy_pass http://portal.zezeping.com/api/${arg_key};
}

proxy upstream

upstream ibrowser_gateway_nodejs_upstream {
    server 127.0.0.1:4000;
    keepalive 64;
}
location / {
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header Host $http_host;
   proxy_set_header X-NginX-Proxy true;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
   proxy_max_temp_file_size 0;
   proxy_pass http://ibrowser_gateway_nodejs_upstream/;
   proxy_redirect off;
   proxy_read_timeout 240s;
  }

websocket/cable配置

location /cable {
  proxy_pass http://ibrowser-backend;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "Upgrade";
}

单页面前端配置

server {
  listen 80; 
  server_name vue3-element-admin.zezeping.com;

  root /var/www/vue3-element-admin;
  index index.html;
  location / {
    try_files $uri $uri/ /index.html =404;
  }
}
wuyuedefeng commented 3 weeks ago

文件根据修改时间来保证浏览器是否重新加载

location ^~ /static/ {
   # 设置文件修改后1分钟的缓存时间
   if_modified_since exact;  # 使用精确的文件修改时间
   # expires 1m;     # 设置文件在请求成功后1分钟过期
   expires -1;  # 设置文件立即过期
   # 添加 ETag 头,帮助浏览器判断文件是否更新
   etag on;
   # 设置 Cache-Control 头以强制浏览器在过期后重新验证文件
   add_header Cache-Control "public, max-age=60";
}