JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

Nginx 备忘录 - 03. location 与 error_page

wys521 2024-10-13 07:59:11 精选教程 16 ℃ 0 评论

一、location 配置

Syntax:	 location [ = | ~ | ~* | ^~ ] uri {...}
         location @name {...}
Default: —
Context: server, location

匹配请求的 URI,并设置相关配置:

  • = :精准匹配。
  • ^~ :精准前缀匹配,匹配成功将不再进行正则匹配。
  • ~ :正则匹配,区分大小写。
  • ~* :正则匹配,不区分大小写。
# 1. 精准匹配
# 只匹配 /,其他 /a, /a/b 不匹配
location = / {} 
# 只匹配 /a,其他 /a/, /ab, /a/b 不匹配
location = /a {}

# 2. 精准前缀匹配
# 匹配任何以 /imgs/ 开头的地址
# 匹配符合以后,停止正则匹配
location ^~ /imgs/ {}

# 3. 正则匹配
# 匹配所有以 gif、jpg 结尾的请求
location ~* \.(gif|jpg)$ {}

# 4. 普通前缀匹配
# 匹配任何以 /a/ 开头的地址
location /a/ {}

# 5. 通用匹配
# 匹配所有地址,如/,/a, /a/, /a/b 等
location / {}

不同类型匹配的顺序:

  • 先匹配精准匹配(=),如果命中则停止匹配;
  • 然后匹配前缀匹配(包括^~),按照最长匹配原则,如果最终命中的为精准前缀匹配(^~)则停止匹配;
  • 最后匹配正则匹配(~, ~*),按照定义顺序匹配,如果命中则停止匹配;

二、name location

这样的 location 不用于常规请求处理,而是用于请求重定向:

# 定义一个名为 liwy_404 的 location
location @liwy_404 {}

# 可以用于请求重定向,如 error_page
error_page 404 = @liwy_404;

三、root 配置

Syntax:  root path;
Default: root html;
Context: http, server, location, if in location

设置请求的根目录,可以是绝对路径或相对路径:

location /i/ {
  root /data/w3;
}

/data/w3/i/top.gif 文件将作为对 /i/top.gif 请求的响应而发送。

四、index 配置

Syntax:  index file ...;
Default: index index.html;
Context: http, server, location

定义 index 文件,文件名可以包含变量,文件按指定顺序检查:

location / {
  index index.0.html /index.html;
}

五、return 配置

Syntax:	 return code [text];
         return code URL;
         return URL;
Default: —
Context: server, location, if

停止处理并将指定的状态码返回给客户端:

# 返回状态码
return 200;
# 返回状态码与内容
return 200 "Hello Liwy!";
# 返回状态码并重定向到指定 URL
return 302 http://www.liwy-nginx-8081.com;
# 重定向到指定 URL
return http://www.liwy-nginx-8081.com;

六、rewrite 配置

Syntax:	 rewrite regex replacement [flag];
Default: —
Context: server, location, if

通过正则匹配重写 URI:

  • regex :正则匹配。
  • replacement :用于替换正则匹配的内容。
  • flag :操作控制符。

flag 标记说明:

  • last :本条规则匹配完成后,继续匹配下一个 location uri。
  • break :本条规则匹配完成后就终止匹配。
  • redirect :返回 302 临时重定向,浏览器地址栏会显示跳转后的 url。
  • permanent :返回 301 永久重定向,浏览器地址栏会显示跳转后的 url。
location /users/ {
  rewrite ^/users/(.*)$ /show?user=$1? last;
  proxy_pass http://liwyservers;
}

七、error_page 配置

Syntax:	 error_page code ... [=[response]] uri;
Default: —
Context: http, server, location, if in location

设置指定错误对应的 URI:

error_page 404 /404.html;
error_page 500 502 503 /50x.html;

# 同时修改状态码
error_page 404 =200 /empty.gif;

# 使用后端服务返回的状态码替换
error_page 404 = /404.php;

# 也可以指定 URL
error_page 403 http://example.com/forbidden.html;

# 与 name location 配合使用
error_page 404 = @liwy_404;
location @liwy_404 {
  default_type text/html;
  return 200 "Liwy 404!!!";
}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表