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

目录

问题描述

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

Nginx文件

shell 复制代码
server {
        listen 80;
        server_name bird.test.com;
        location / {
        		root /app/code/bird/;
                index index.html;
        }
#uri 包含 html、js、css 结尾的文件缓存一天
#~* 后支持正则表达式
        location ~* \.(html|js|css)$ {
                expires 1d;
        }
        location ~* \.(jpg|jpeg|png|gif|bmp)$ {
                expires 1h;
        }
}

解决方案

查看error_log日志

shell 复制代码
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文件

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

测试

缓存设置成功。

  • 日志:
shell 复制代码
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。
相关推荐
tz5256 小时前
Superpowers 游戏开发实战应用场景大纲
linux·运维·服务器
倔强的石头_6 小时前
Linux 电脑也能被 UU 远程连进去了:Linux PC 端内测上手,主控和被控我都试了
运维
Decay__10 小时前
PostgreSQL WAL 归档与时间点恢复 —— WAL 连续归档、recovery_target 时点恢复与 pg_rewind
运维·数据库·sql·postgresql
船神丿男人12 小时前
Redis 缓存击穿与雪崩实测:同键合并、TTL 错峰与迟到回填
数据库·redis·缓存
Decay__13 小时前
PostgreSQL 索引与 SQL 优化 —— B-tree、GiST、GIN、BRIN、执行计划与索引设计实战
运维·数据库·sql·postgresql
JWIPC14 小时前
MyClaw 3.0 自动化数据采集实战指南
linux·运维·笔记·科技·深度学习·物联网·自动化
Kainy14 小时前
生产服务器从机械盘迁移NVMe固态:旧盘不动、退路先行的六步实操全记录
运维·服务器
جيون داد ناالام ميづ14 小时前
六、MyBatis 高级用法:动态 SQL 进阶 + 缓存优化 + TypeHandler
sql·缓存·mybatis
Henry-SAP16 小时前
SAP BOM项目类别详解——L/T/R/N各类目的业务含义解析
运维
op_qo16 小时前
写了几年 OpenResty Lua 网关脚本,聊聊绕不开的 5 个痛点与一种新解法
nginx