location指令是http模块当中最核心的一项配置,根据预先定义的URL匹配规则来接收用户发送的请求,根据匹配结果,将请求转发到后台服务器、非法的请求直接拒绝并返回40三、40四、500错误处理等。html
location [=|~|~*|^~|@] /uri/ { … } 或 location @name { … }
nginx
location指令分为两种匹配模式:正则表达式
先匹配普通字符串模式(普通匹配,匹配到会暂存,继续搜索正则匹配),再匹配正则模式(正则模式匹配到,即为最终匹配)
。只识别URI部份,例如请求为:/test/abc/user.do?name=xxxx 一个请求过来后,Nginx匹配这个请求的流程以下:location /test/ { … }
location /test/abc { … }
复制代码
location =/ { … }
与 location / { … }
的差异:缓存
location ~ /test/.+.jsp$ { … }
:正则匹配,支持标准的正则表达式语法。 location ^~ / { … }
: ^~意思是关闭正则匹配,当搜索到这个普通匹配模式后,将再也不继续搜索正则匹配模式。bash
http {
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
# deny all; 拒绝请求,返回403
# allow all; 容许请求
}
location /abc {
deny all;
}
location ~ /.+\.jsp$ {
proxy_pass http://location:9090;
}
# 匹配全部/test路径下的jsp文件
location ~ /test/.+\.jsp$ {
proxy_pass http://localhost:8080;
}
# 定义各种错误页
error_page 404 /404.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# @相似于变量定义
# error_page 403 http://blog.csdn.net; #这种定义不容许,需求利用@定义临时变量来实现
error_page 403 @page403;
location @page403 {
proxy_pass http://blog.csdn.net;
}
}
}
复制代码