server {
#监听端口
listen 80;
#域名
server_name localhost;
#编码
charset koi8-r;
#日志
access_log /var/log/nginx/host.access.log main;
#直接输入域名进入的目录和默认解析的文件
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#错误页
error_page 500 502 503 504 /50x.html; location = /50x.html {
root /usr/share/nginx/html;
}
#禁止访问.htxxx文件 location ~ /\.ht { deny all;
}
2、Location匹配规则
= | 精确匹配,匹配成功则停止匹配 |
八〜 | 前缀普通字符匹配,匹配成功则停止匹配 |
〜 | 正则匹配,区分大小写;多个正则按顺序匹配 |
〜* | 正则匹配,不区分大小写;多个正则按顺序匹配 |
!〜 | 正则不匹配,区分大小写;多个正则按顺序匹配 |
!〜* | 正则不匹配,不区分大小写;多个正则按顺序匹配 |
@ | 定义一个命名的location,使用在内部重定向时,例如error_page,try_files |
/ | 通用匹配,未匹配到location的都会匹配到此 |
2.1、“=”精确匹配示例
server { | |
listen | 80; |
server_name | localhost; |
location / | { |
root | /usr/share/nginx/html; |
index | index.html index.htm; |
} | |
location = | /baidu.html { |
root | /etc/nginx/html/; |
} | |
} |
访问:curl http://localhost/baidu・html,实际访问的路径问/etc/nginx/html/baidu・html
<html>
<head>
<title >测试 </title>
</head>
<body> baidu </body>
</html>
2.2、"八~”前缀普通字符匹配
server { listen 80;
server_name localhost; location / {
root /usr/share/nginx/html; index index.html index.htm;
}
location 八~ /tea/ {
root /etc/nginx/html/;
}
访问:curl http://localhost/tea/tea1 ・html,实际访问的路径问/etc/nginx/html/tea/teal .html
<html>
<head>
<title >测试 </title>
</head>
<body>
tea
</body>
</html>
2.3、“~”区分大小写正则匹配
server {
listen | 80; |
server_name | localhost; |
#charset koi8-r;
#access_log | /var/log/nginx/host.access.log main; |
location / {
root /usr/share/nginx/html; index index.html index.htm;
}
location ~ \.html$ { root /etc/nginx/html/;
}
访问:curl http://localhost/baidu・html,实际访问的路径问/etc/nginx/html/baidu・html
<html>
<head>
<title >测试 </title>
</head>
<body>
baidu
</body>
</html>
访问:curl http://localhost/baidu.HTML,匹配不成功,实际访问的路径
问/us r/sha re/nginx/html/baidu ・H TML
2.4、"~*”不区分大小写正则匹配
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location ~* \.html$ {
root /etc/nginx/html/;
}
访问:curl http://localhost/baidu・HTML,匹配成功,实际访问的路径问/etc/nginx/html/baidu.HTML
<html>
<head>
<title >测试 </title>
</head>
<body>
baidu
</body>
</html>
2.5、 "!~ ”区分大小写正则不匹配
location ($host !~ "八www\.") {
root /etc/nginx/html/;
2.6、 "!~* ”不区分大小写正则不匹配
location ($host !~* "八www\.") {
root /etc/nginx/html/;
2.7、 ”@” nginx内部跳转
server { listen 80;
server_name localhost;
location = /baidu { error_page 404 @page_err;
}
location @page_err { root /etc/nginx/html/;
}
访问:curl http://localhost/baidu・htm,返回404,实际访问的路径问/etc/nginx/html/baidu・htm