Nginx设置缓存后,访问网页404 问题原因及解决方案(顺手记)

[复制链接]
发表于 2024-6-19 21:02:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
问题描述

在Nginx中设置缓存expires后,结果重启nginx,网站访问404了。
Nginx文件

  1. server {
  2.         listen 80;
  3.         server_name bird.test.com;
  4.         location / {
  5.                         root /app/code/bird/;
  6.                 index index.html;
  7.         }
  8. #uri 包含 html、js、css 结尾的文件缓存一天
  9. #~* 后支持正则表达式
  10.         location ~* \.(html|js|css)$ {
  11.                 expires 1d;
  12.         }
  13.         location ~* \.(jpg|jpeg|png|gif|bmp)$ {
  14.                 expires 1h;
  15.         }
  16. }
复制代码
解决方案

查看error_log日志日志

  1. 2024/06/05 00:00:17 [error] 3189#3189: *1 open() "/etc/nginx/html/index.html" failed (2: No such file or directory), client: 192.168.100.1, server: bird.test.com, request: "GET /index.html HTTP/1.1", host: "bird.test.com"
复制代码
由上可以发现,在访问时,哀求的URI是/etc/nginx/html/index.html,而不是在 location中指定的root /app/code/bird/index.html。
问题原因



  • Nginx中location模块是独立的,因此在不同的locaiton中,root不共享。
  • 在Nginx子配置文件中,我将root语句写在location内,再新建location写expires后,这两个location实在并不是一个。
  • 因此在匹配到正则的.html后,访问了默认的nginx路径,导致文件不存在。
修改文件并测试

Nginx文件

  1. server {
  2.         listen 80;
  3.         server_name bird.test.com;
  4.         root /app/code/bird/; # 每个location区域都是独立的,如果root写在location内,则在指定缓存时的location中也要添加上root
  5.         location / {
  6.                 index index.html;
  7.         }
  8. #uri 包含 html、js、css 结尾的文件缓存一天
  9. #~* 后支持正则表达式
  10.         location ~* \.(html|js|css)$ {
  11.                 expires 1d;
  12.         }
  13.         location ~* \.(jpg|jpeg|png|gif|bmp)$ {
  14.                 expires 1h;
  15.         }
  16. }
复制代码
测试


   缓存设置乐成。
  
  1. 192.168.100.1 - - [05/Jun/2024:00:11:15 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
复制代码
总结



  • Nginx中,location内的配置是独立的,不同location不共享配置。
  • 假如必要设置缓存:

    • 要么在原location中直接设置
    • 要么在新location中重制定root
    • 要么直接在server下写root。

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表