http块的作用: 配置所有server通用的一些配置
include mime.types; # 文件扩展名与文件类型映射表
default_type application/octet-stream; # 默认文件类型
sendfile on; # 开启高效文件传输模式。
autoindex on; # 开启目录列表访问,合适下载服务器,默认关闭。
tcp_nopush on; # 防止网络阻塞
tcp_nodelay on; # 防止网络阻塞
keepalive_timeout 120; # 长连接超时时间,单位是秒
gzip on; # 开启gzip压缩输出
1 server
# 虚拟主机的配置,一个server就代表一个虚拟主机
server {
# 监听端口
listen 192.168.250.130:80;
# 域名可以有多个, 用空格隔开
server_name www.meiduo.site;
# 资源定位
location =/{
# 站点根目录,你网站文件存放的地方
root /home/ws/Desktop/meiduo/meiduo_mall/meiduo_mall/static;
index index.html;
}
}
(1) location
location主要是根据Server匹配到的请求路径和关键字去响应和处理。
location[ = | ~ | ~* | ^~] url{
}
=:用于不含正则表达式的 url 前,要求字符串与 url 严格匹配,匹配成功就停止向下搜索并处理请求。
~:用于表示 url 包含正则表达式,并且区分大小写。
!~:用于表示 url 包含正则表达式,并且不区分大小写。
~*:用于表示 url 包含正则表达式,并且不区分大小写。
!~*:用于表示 url 包含正则表达式,并且区分大小写。
^~:用于不含正则表达式的 url 前,要求 Nginx 服务器找到表示 url 和字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再匹配。
如果有 url 包含正则表达式,不需要有 ~ 开头标识。
优先级: 精确匹配 > 优先匹配 > 通用匹配
访问效果如下:
访问根目录/, 比如http://a.com/ 将匹配规则A
访问 http://a.com/login 将匹配规则B
访问 http://a.com/static/a.html 将匹配规则C
访问 http://a.com/a.gif, http://a.com/b.png 规则D和E均适合,按顺序优先使用规则D
http://a.com/static/c.png 则优先匹配到规则C
http://a.com/a.PNG 则匹配规则E,因为规则E不区分大小写。
访问 http://a.com/a.XHTML 使用规则F。
访问 http://a.com/category/id/1111 则最终匹配到规则H。
1) try_files
try_files $uri $uri/ =400;
当用户请求 http://localhost/example 时,这里的 $uri 就是 /example。
它会先到root/下找example这个文件,
若没有找到, 就到$uri目录下找, 即root/example/中找
若还没有找到, 就会返回状态码400
location / {
root /etc/nginx/html;
index index.html;
try_files $uri $uri/ =400; # try_files对根路径无效
}
location /a {
try_files $uri $uri/ =401;
}
搭配@使用
location /a {
try_files $uri $uri/ @meiduo;
}
location @meiduo {
return 402;
}
2) return
location / {
return 301 http://www.baidu.com;
}
3) alias
location / {
alias /etc/nginx/html/; # alias一定要在末尾加/, root加不加都可以
index 111.html;
}
location /a { # 请求/a路径 等价于 请求/etc/nginx/html/
alias /etc/nginx/html/; # alias相当于给后面的路径取了个别名叫/a
index 111.html;
}
location /html { # 请求/html路径 等价于 请求/etc/nginx/html/
root /etc/nginx/; # root是指根路径, 这里是在根路径上追加/html
index 111.html;
}
4) stub_status
location / {
stub_status on; # 返回nginx状态信息
}
5) allow deny
location / {
allow 192.168.250.1; # 允许哪个IP访问
deny all; # 除了允许的IP, 其它都拒绝访问
}
6) autoindex
打开目录浏览功能, 可下载文件
location /cctv {
alias /home/ws/;
autoindex on;
}