Nginx — http、server、location模块下配置相同策略优先级问题

一、配置优先级简述

在 Nginx 中,httpserverlocation 模块下配置相同策略时是存在优先级的,一般遵循 "范围越小,优先级越高" 的原则,下面为你详细介绍:

1. 配置继承关系

  • http :作为全局配置块,其中的配置会对所有的 server 块生效,属于最宽泛的配置范围。
  • server :定义虚拟主机,其配置会覆盖 http 块中相同的配置,适用于特定的域名或 IP 地址。
  • location :处于 server 块内部,用于匹配特定的 URI 路径,其配置会覆盖 server 块和 http 块中相同的配置,是最精细的配置范围。

二、实验验证

以日志配置为例

实验准备:

步骤一:在http模块定义日志

配置在http块下配置日志

bash 复制代码
http {
    ...
    #配置日志
    log_format myformat '访问URL: $request_uri';
    access_log logs/http.log myformat;
    ...
}

步骤二:在server和location块下定义日志

bash 复制代码
server {
    ...
    access_log logs/server.log myformat;
    ...

    location /location {
        ...
        access_log logs/location.log myformat;
        ...
    }
}

步骤三:定义两个server 三个访问url

server配置

bash 复制代码
server {
    listen      443 ssl;
    ssl_certificate /usr/local/nginx/conf/ssl/gateway.crt;
    ssl_certificate_key /usr/local/nginx/conf/ssl/gateway.key;
    server_name  192.168.72.130;
    root /opt/xxx;
    location /http {
        #这里设置内部重定向,将http开头的请求重定向到根目录下
        rewrite ^/http(.*)$ /$1 break;
        # 开启目录列表展示功能
        autoindex on;
        # 以可读格式显示文件大小
        autoindex_exact_size off;
        # 以本地时间显示文件修改时间
        autoindex_localtime on;
        }
}

server {
    listen 80;
    server_name 192.168.72.130;  # 替换为你的域名
    gzip on;
    #配置日志
    access_log logs/server.log myformat;

    # 网站根目录,即要暴露内容的目录
    root /opt/xxx;

    location /server {
        #这里设置内部重定向,将server开头的请求重定向到根目录下
        rewrite ^/server(.*)$ /$1 break;
        # 开启目录列表展示功能
        autoindex on;
        # 以可读格式显示文件大小
        autoindex_exact_size off;
        # 以本地时间显示文件修改时间
        autoindex_localtime on;
    }

    location /location {
        #这里设置内部重定向,将 /location 开头的请求重定向到根目录下
        rewrite ^/location(.*)$ /$1 break;
        #配置日志
        access_log logs/location.log myformat;
        # 开启目录列表展示功能
        autoindex on;
        # 以可读格式显示文件大小
        autoindex_exact_size off;
        # 以本地时间显示文件修改时间
        autoindex_localtime on;
    }
}

三、实验结果

因为在location中有定义日志所以日志输出直接采用location中的策略

因为在location中没有定义日志所以日志输出采用server中的策略

因为在location和server中都没有定义日志,所以日志输出采用server中的策略

结论:

在 Nginx 中,httpserverlocation 模块下配置相同策略时是存在优先级的,一般遵循 "范围越小,优先级越高" 的原则,

相关推荐
志栋智能1 天前
超自动化运维:如何降低人为错误?
大数据·运维·网络·人工智能·自动化
武器大师721 天前
从零开始在 Linux 上编译运行 lvgljs 图形界面项目
linux·运维·服务器
剑神一笑1 天前
Linux free 命令深度解析:从内存监控到 OOM 排查的完整指南
linux·运维·服务器
蘑菇丁1 天前
招聘大数据运维工程师(郑州)
大数据·运维
NiceCloud喜云1 天前
Claude Code 跑 HyperFrames 实测:本地生成 AI 视频素材全流程
java·运维·人工智能·自动化·json·音视频·飞书
qq_312920111 天前
服务器被攻击!完整安全加固清单汇总
运维·服务器·安全
leaves falling1 天前
深入理解Linux进程控制:从fork到exec,手写一个迷你Shell
linux·运维·服务器
cd_949217211 天前
水处理市场升级,台州海德能环保科技凭技术创新与服务并重脱颖而出
大数据·运维·科技
.YYY1 天前
万字详解|Linux Chrony 时间服务完整学习手册
linux·运维
Li-Yongjun1 天前
Linux 内核等待队列(Wait Queue)
linux·运维·windows