CodeAshen's blog CodeAshen's blog
首页
  • Spring Framework

    • 《剖析Spring5核心原理》
    • 《Spring源码轻松学》
  • Spring Boot

    • Spring Boot 2.0深度实践
  • Spring Cloud

    • Spring Cloud
    • Spring Cloud Alibaba
  • RabbitMQ
  • RocketMQ
  • Kafka
  • MySQL8.0详解
  • Redis从入门到高可用
  • Elastic Stack
  • 操作系统
  • 计算机网络
  • 数据结构与算法
  • 云原生
  • Devops
  • 前端
  • 实用工具
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
  • Reference
GitHub (opens new window)

CodeAshen

后端界的小学生
首页
  • Spring Framework

    • 《剖析Spring5核心原理》
    • 《Spring源码轻松学》
  • Spring Boot

    • Spring Boot 2.0深度实践
  • Spring Cloud

    • Spring Cloud
    • Spring Cloud Alibaba
  • RabbitMQ
  • RocketMQ
  • Kafka
  • MySQL8.0详解
  • Redis从入门到高可用
  • Elastic Stack
  • 操作系统
  • 计算机网络
  • 数据结构与算法
  • 云原生
  • Devops
  • 前端
  • 实用工具
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
  • Reference
GitHub (opens new window)
  • RabbitMQ

  • RocketMQ

  • Kafka

  • Nginx

    • 第01章-基础篇
    • 第02章-场景实践篇
    • 第03章-深度学习篇
    • 第04章-架构篇
      • 4.1 Nginx常见问题
        • 4.1.1 相同server_name多个虚拟主机优先级
        • 4.1.2 location匹配优先级
        • 4.1.3 try_files使用
        • 4.1.4 Nginx的alias和root区别
        • 4.1.5 传递用户真实IP
  • 中间件
  • Nginx
CodeAshen
2023-02-10
目录

第04章-架构篇

# 4.1 Nginx常见问题

# 4.1.1 相同server_name多个虚拟主机优先级

image-20210803162722397

当多个同名 server_name,优先走先读取到的配置

  • 写在同一配置文件里的,走写在上面的
  • 写在不同配置文件里的,走文件名排序靠前的

# 4.1.2 location匹配优先级

  1. =:进行普通字符精确匹配,也就是完全匹配
  2. ^~:表示普通字符匹配,使用前缀匹配
  3. ~ \~*:表示执行一个正则匹配

请求来了,从上到下,如果匹配到前两个,则不再继续匹配,直接走相应的location;如果匹配到正则匹配,还将继续向下匹配,看有没有更匹配的location。

# 精确匹配
location = /code1/ {
    rewrite ^(.*)$ /code1/index.html break;
}

# 前缀匹配
location ^~ /code {
    rewrite ^(.*)$ /code2/index.html break;
}

# 正则匹配
location ~ /code.* {
    rewrite ^(.*)$ /code3/index.html break;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 4.1.3 try_files使用

try_files 用于按顺序检查文件是否存在,存在就直接返回

location / {
    try_files $uri $uri/ /index.php;
}
1
2
3

# 4.1.4 Nginx的alias和root区别

root 和 alias 都用于讲请求指向本地文件,不过指向方式不同

location /request_path/image/ {
    root /local_path/image/;
}
1
2
3
location /request_path/image/ {
    alias /local_path/image/;
}
1
2
3

对于上述两个配置,如果请求路径为 http://localhost/request_path/image/cat.png,root和alias将请求不同的文件:

  • root: /local_path/image/request_path/image/cat.png
  • alias: /local_path/image/cat.png

# 4.1.5 传递用户真实IP

image-20210803165207159

当用户请求经过多级代理到达后端服务器的时候,通过 x_forwarded_for 获取的ip往往不准确,且容易被篡改。

image-20210803165404231

可以再一级代理处将用户ip添加到指定请求头 x_real_ip 中,后续的服务通过该请求头获取用户ip。

编辑 (opens new window)
上次更新: 2023/06/04, 12:34:19
第03章-深度学习篇

← 第03章-深度学习篇

最近更新
01
第01章-RabbitMQ导学
02-10
02
第02章-入门RabbitMQ核心概念
02-10
03
第03章-RabbitMQ高级特性
02-10
更多文章>
Theme by Vdoing | Copyright © 2020-2023 CodeAshen | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式