Nginx由Nginx内核和模块组成。
客户请求到达Nginx web服务器,Nginx 会去将请求通过查找配置文件的方式,进行匹配,将客户端的请求匹配到配置文件中的location block,location block 就会调用内部的其他模块进行处理。
而location是Nginx配置中的一个指令,用于访问的URL匹配,而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。
Nginx主配置文件:
yum 安装默认文件位置:/etc/nginx/nginx.conf
源码安装默认文件位置:/usr/local/nginx/conf/nginx.conf
Nginx 发布路径:
yum 默认发布路径:/usr/share/nginx/html/
源码默认发布路径:/usr/local/nginx/html/
location 示例文件
# location是Nginx配置中的一个指令,用于访问的URL匹配,而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。
示例请求:http://www.baidu.com / ------>后端发布百度网站nginx服务器,服务器处理这个url,将url和nginx内部的配置location进行规则匹配。匹配到对应的location,此location规则就生效,由此location内部规则模块处理该请求。
location / {
root html;
index index.html;
}
示例请求:http://www.baidu.com/test.php
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/ngin/html$fastcgi_script_name;
include fastcgi_params;
}
示例请求:http://www.baidu.com/40x.html
location = /40x.html {
}
#多个location之间是有优先级的。根据location不同书写规则进行设定的。
#nginx处理客户请求,是根据客户不同的url访问路径和nginx,内部配置location相互就进行匹配。
#如果想要域名匹配location /newindex/ { }
那么这个域名应该是http://www.baidu.com/newindex/
location 规则匹配
location 规则匹配分为普通字符匹配,正则表达式匹配
其中Location = 和location ^~和location /属于普通字符串匹配
Location ~、~*属于正则表达式匹配。
location = / {
[ configuration L1 ]
#只会匹配/,优先级比Location /低。
}
location = /index.html {
[ configuration L2 ]
#只会匹配/index.html,优先级最高。
}
location / {
[ configuration L3 ]
#匹配任何请求,因为所有请求都是以"/"开始;
#但是更长字符匹配或者正则表达式匹配会优先匹配,优先级最低。
}
location = /images/ {
[ configuration L4 ]
#匹配任何以/images/开始的请求,并停止匹配其它location;
}
location ~* \.(html|txt|gif|jpg|jpeg)$ {
[ configuration L5]
#匹配以html、txt、gif、jpg、jpeg结尾的URL文件请求;
#但是所有/images/目录的请求将由 [Configuration L4]处理。
}
浏览器发起HTTP Request URI案例与Location规则案例匹配如下:
/ ->匹配configuration L3;
/index.html匹配configuration L2;
/images/匹配configuration L4;
/images/logo.png匹配configuration L4;
/img/test.jpg匹配configurationL5。
#配置文件:
location = /jfedu.html {
root /usr/share/nginx/html/jfedu/;
}
#root参数代表web页面发布路径。
#url路径:http://10.0.0.7/jfedu.html
#真实服务器上面的路径:/usr/share/nginx/html/jfedu/jfedu.htm