第04章-架构篇
# 4.1 Nginx常见问题
# 4.1.1 相同server_name多个虚拟主机优先级
当多个同名 server_name
,优先走先读取到的配置
- 写在同一配置文件里的,走写在上面的
- 写在不同配置文件里的,走文件名排序靠前的
# 4.1.2 location匹配优先级
=
:进行普通字符精确匹配,也就是完全匹配^~
:表示普通字符匹配,使用前缀匹配~ \~*
:表示执行一个正则匹配
请求来了,从上到下,如果匹配到前两个,则不再继续匹配,直接走相应的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
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
2
3
# 4.1.4 Nginx的alias和root区别
root
和 alias
都用于讲请求指向本地文件,不过指向方式不同
location /request_path/image/ {
root /local_path/image/;
}
1
2
3
2
3
location /request_path/image/ {
alias /local_path/image/;
}
1
2
3
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
当用户请求经过多级代理到达后端服务器的时候,通过 x_forwarded_for
获取的ip往往不准确,且容易被篡改。
可以再一级代理处将用户ip添加到指定请求头 x_real_ip
中,后续的服务通过该请求头获取用户ip。
编辑 (opens new window)
上次更新: 2023/06/04, 12:34:19