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

问题描述

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

Nginx文件

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日志

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文件

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;
        }
}

测试

在这里插入图片描述

缓存设置成功。

  • 日志:
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

相关推荐

  1. nginx405 not allowed问题解决方法

    2024-06-08 12:20:06       40 阅读
  2. nginx405 not allowed问题解决方法

    2024-06-08 12:20:06       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 12:20:06       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 12:20:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 12:20:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 12:20:06       18 阅读

热门阅读

  1. Vue Router——hash模式和 history模式

    2024-06-08 12:20:06       10 阅读
  2. Elasticsearch 认证模拟题 - 10

    2024-06-08 12:20:06       10 阅读
  3. TCP和udp能使用同一个端口通讯吗

    2024-06-08 12:20:06       8 阅读
  4. 设计模式总结

    2024-06-08 12:20:06       6 阅读
  5. UVa1116/LA2429 Puzzle

    2024-06-08 12:20:06       5 阅读
  6. #07 使用Stable Diffusion生成高质量图片的技巧

    2024-06-08 12:20:06       8 阅读
  7. HTTP参数污染漏洞

    2024-06-08 12:20:06       8 阅读
  8. 速盾:图片cdn托管

    2024-06-08 12:20:06       9 阅读
  9. 挣值计算中的典型与非典型

    2024-06-08 12:20:06       8 阅读