一、显示文件目录
Nginx 默认不允许列出整个目录浏览下载。
Enables or disables the directory listing output.
Syntax: autoindex on | off;
Default: autoindex off;
Context: http, server, location
autoindex 常用参数:
autoindex_exact_size off; 默认为on, 显示文件的准确大小,单位是bytes。改为 off, 显示单位是kB/MB/GB
autoindex_localtime on; 默认为off, 显示文件时间为GMT时间。改为on,显示为服务器时间。
charset utf-8, gbk; 默认中文目录乱码,添加上后解决乱码。
location /data {
root /application/nginx/shop;
autoindex on;
autoindex_localtime on;
autoindex_exact_size off;
charset utf-8,gbk;
}

[root@my-node10 data]# ls
中文1988 aa.txt ab.txt dd.log
二、 try_files: 按顺序检查文件是否存在
location / {
try_files $uri $uri/ /index.php;
}
检查用户请求的uri内容 是否存在本地, 存在则解析
将请求加/, 类似于重定向处理
最后交给index.php处理。
location / {
index index.html;
try_files $uri @java_page;
}
location @java_page {
proxy_pass http://192.168.6.51:8081;
}
三、 alias 与 root 区别
curl http://192.168.6.10:8300/request_path/code/index.html
location /request_path/code/ {
root d1/;
}
# nginx -V 显示前缀 是 --prefix=/etc/nginx
2023/03/11 22:06:16 [error] 1667#1667: *42 open() "/etc/nginx/d1/request_path/code/index.html" failed (2: No such file or directory),
client: 192.168.6.51, server: www.mydemo.com, request: "GET /request_path/code/index.html HTTP/1.1", host: "192.168.6.10:8300"
location /request_path/code/ {
root /application/nginx/demo/d1/;
}
2023/03/11 22:06:57 [error] 1674#1674: *43 open() "/application/nginx/demo/d1/request_path/code/index.html" failed
(2: No such file or directory), client: 192.168.6.51, server: www.mydemo.com,
request: "GET /request_path/code/index.html HTTP/1.1", host: "192.168.6.10:8300"
alias
location /request_path/code/ {
alias /application/nginx/demo/d1/;
}
# 访问 /application/nginx/demo/d1/index.html
[root@my-node51 ~]# curl http://192.168.6.10:8300/request_path/code/index.html
d1-1
四、 location 匹配优先级
- = 进行普通字符精确匹配, 完全匹配
- ^~ 普通字符匹配, 使用前缀匹配, 以什么开头
- 正则匹配 匹配后继续查找更准确匹配的location
- ~ 匹配区分大小写
- ~* 不区分大小写
[root@my-node10 ~]# cd /application/nginx/demo/ [root@my-node10 demo]# ls 1.html d1 d2 d3 demo.html image.html index.html [root@my-node10 conf.d]# cat demo-dd.conf server { listen 80; server_name 192.168.6.10; root /application/nginx/demo; location = /dd1/ { rewrite ^(.*)$ /d1/index.html break; } location ~ /dd* { rewrite ^(.*)$ /d3/index.html break; } location ^~ /dd { rewrite ^(.*)$ /d2/index.html break; } }
[root@my-node51 ~]# curl http://192.168.6.10/dd1/ d1-1 [root@my-node51 ~]# curl http://192.168.6.10/dd d2-1 [root@my-node51 ~]# curl http://192.168.6.10/dd4 d2-1 [root@my-node51 ~]# curl http://192.168.6.10/d d3-1
# 注销掉 精确匹配 =, 重启Nginx [root@my-node51 ~]# curl http://192.168.6.10/dd1/ d2-1 [root@my-node51 ~]# curl http://192.168.6.10/dd d2-1 [root@my-node51 ~]# curl http://192.168.6.10/dd4 d2-1 [root@my-node51 ~]# curl http://192.168.6.10/d d3-1