1、部署单个站点
server { listen 80; server_name localhost; location / { root /app; index index.html; try_files $uri $uri/ /index.html; } }
2、部署多个站点
server { listen 80; listen 443 ssl http2; server_name www.demo.com; if ($ssl_protocol = "") { return 301 https://$host$request_uri; } # 前端 location / { root /data/wwwroot/www; index index.html; try_files $uri $uri/ /index.html; } # 后台 location ^~/admin { alias /data/wwwroot/admin; try_files $uri $uri/ /admin/index.html; } # 数据接口 location /api { proxy_pass http://127.0.0.1:5000; } }
3、缓存问题解决
浏览器缓存分类:
1、强制缓存
Expires:依赖本地时间和服务器时间
Cache-control:max-age=10
2、协商缓存
last-modified:文件修改时间
ETag:文件指纹
3、禁用缓存
Cache-control:no-store
html默认当做了静态文件传输,会被浏览器缓存,每次打开都拿不到最新的页面
使用Charles抓包发现:
访问网站首页压根没有进行请求,直接从浏览器本地获取了index.html文件。
看来浏览器使用了强制缓存策略,nginx 添加以下配置,告诉浏览器怎么缓存html文件:
# 对html文件限制缓存 location ~ .*\.(html)$ { # 不缓存 # add_header Cache-Control no-store; # 或者用 协商缓存 add_header Cache-Control no-cache; add_header Pragma no-cache; } # css/js文件 location ~ .*\.(js|css)?$ { # 缓存有效期:7天 expires 7d; access_log off; } # 图片资源 location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ { expires 30d; access_log off; }
参数 | 说明 |
Cache-Control: no-cache | 协商缓存,只能应用于http 1.1,会返回304(资源无更新) |
Cache-Control: no-store | 禁止缓存 |
Pragma: no-cache | 和 Cache-Control: no-cache 相同,应用于 http 1.0 和http 1.1 |
协商缓存的参数
Last-Modified / IF-Modified-Since 验证修改时间
Etag / IF-None-Match 验证文件指纹
版权声明:
本文为CSDN博主「彭世瑜」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。