nginx重定向(rewrite、return、if 和 set 指令)
本文最后更新于15 天前,其中的信息可能已经过时,如有错误请发送邮件到big_fw@foxmail.com

Ⅰ、return 指令

一,基本语法

return code [text];
return code URL;
return URL;  # 默认使用302状态码
注:无法使用正则
参数描述
codeHTTP 状态码 (如 301, 302, 404, 503 等)
text直接返回的响应体内容(适用于非3xx状态码)
URL重定向目标地址(适用于3xx重定向状态码)

官网详解地址:Module ngx_http_rewrite_module

二,案例使用

  • 网站是http(80)–>https(443) URL重定向
  • 新老域名跳转: www.360buy.com —> jd.com
  • 需要我们调整url格式:伪静态(搜索引擎收入) 运营要求

1.重定向类(301,302)

案例1、域名跳转,旧域名跳转新域名

# 域名变更
server {
    listen 80;
    server_name old-domain.com;
    return 301 http://www.baidu.com; #301永久跳转
}
server {
    listen 80;
    server_name old-domain.com;
    return 301 http://www.baidu.com$request_uri; #$request_uri作用是报证uri不变,例如访问old-domain.com/img/2025,跳转地址就是http://www.baidu.com/img/2025
}

案例2、HTTP跳转HTTPS

server {
    listen 80;
    server_name domain.com;
    return 301 https://new-domain.com$request_uri;
}

# HTTP跳转HTTPS
server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name https://new-domain.com;
    root /app/code/rewrite/;
    私钥
    公钥(证书)
    location / {
        index index.html;
    }
 }

2. 4xx 客户端错误类

案例1、用户访问/admin/返回403

server {
  listen 80;
  server_name daemon.com;
  root /app/code/rewrite; 
  location / {
    index index.html;
  }
  location /admin/ {
    return 403;
  }
 }

案例2、禁止特定ip访问

location /admin {
    deny 192.168.1.100;
    allow all;
    return 403 "Access Denied - Your IP has been logged";
}

3. 5xx 服务端错误类

# 维护模式
location / {
    return 503 "Service Temporarily Unavailable\nPlease try again later";
    add_header Retry-After 3600;
}

# 配合error_page
error_page 503 /maintenance.html;
location = /maintenance.html {
    internal;
    root /var/www/html;
}

Ⅱ、rewrite指令

  • rewrite正则用于匹配用户请求的uri
  • 命令的格式与sed ‘s###g’ 类似,实现替换功能,rewrite替换url内容.

一、rewrite 基本语法

rewrite regex replacement [flag];

1.参数说明:

  • regex:用于匹配 URI 的正则表达式
  • replacement:替换后的目标 URI
  • flag:标志位,控制重写行为

二、flag 标志详解

以下是 Nginx rewrite 指令支持的标志(flag)汇总表格,包含各标志的作用、执行流程和典型使用场景:

标志描述执行流程
last停止处理当前rewrite 规则,并用重写后的 URI 重新匹配 location 块1. 重写 URI
2. 重新从第一个 location 开始匹配
break停止所有rewrite 处理,直接使用当前重写结果继续后续处理1. 重写 URI
2. 跳过后续 rewrite 规则
3. 继续处理当前 location
redirect返回302 临时重定向(显式跳转,浏览器地址栏变化)1. 立即返回 302 响应
2. 响应头包含 Location: new-uri
permanent返回301 永久重定向(显式跳转,浏览器和搜索引擎会更新缓存)1. 立即返回 301 响应
2. 响应头包含 Location: new-uri
(无标志)默认行为:重写 URI 后继续处理后续规则1. 重写 URI
2. 继续执行下一条 rewrite 规则

三、案例使用

案例1、HTTP–>HTTPS 跳转

server {
    listen 80;
    server_name example.com;
    rewrite ^(.*)$ https://example.com$1 permanent;
}

案例2、伪静态化(隐藏 .php 扩展名)

#场景:将 /user/123 映射到 /user.php?id=123

location /user {
    rewrite ^/user/(\d+)$ /user.php?id=$1 last;
}
#场景:将 /en/about 转换为 /?lang=en&page=about
rewrite ^/(en|zh)/(about|contact)$ /?lang=$1&page=$2 last;

案例3,flag标志案例

1. last

  • 停止处理当前 rewrite 规则
  • 用重写后的 URI 重新匹配 location
server {
   listen 80;
   server_name daemon.com;
   root /app/code/flag;
   error_log /var/log/nginx/flag-error.log notice;
   rewrite_log on; #需要错误日志debug ... notice
   location / {
    rewrite /1.html /2.html  laset;
    rewrite /2.html /3.html ;
   }
   location /2.html {
     rewrite /2.html /b.html ;
   }
   location /3.html {
      rewrite /3.html /a.html ;
   }
 }

访问http://daemon.com/1.html
输出结果是b.html
流程:
1.请求 /1.html 进入 location /
2.执行第一条 rewrite 规则:/1.html → /2.html,遇到 last 标志
3.停止当前 rewrite 处理,重新开始 location 匹配,现在 URI 是 /2.html
4.匹配到 location /2.html,执行其中的 rewrite:/2.html → /b.html
5.因为没有 last 或 break 标志,继续处理(但这里没有更多 rewrite 规则了)
6.最终返回 /app/code/flag/b.html 的内容

2. break

  • 停止所有 rewrite 处理
  • 直接使用当前重写结果
server {
   listen 80;
   server_name daemon.com;
   root /app/code/flag;
   error_log /var/log/nginx/flag-error.log notice;
   rewrite_log on; #需要错误日志debug ... notice
   location / {
    rewrite /1.html /2.html  break;
    rewrite /2.html /3.html ;
   }
   location /2.html {
     rewrite /2.html /b.html ;
   }
   location /3.html {
      rewrite /3.html /a.html ;
   }
 }

访问http://daemon.com/1.html
输出结果是2.html
流程:
1.请求 /1.html 进入 location /
2.执行第一条 rewrite 规则:/1.html → /2.html,遇到 break 标志
3.停止所有 rewrite 处理(包括当前 location 和后续的 rewrite)
4.不重新匹配 location,直接使用当前 URI /2.html
5.查找文件 /app/code/flag/2.html 并返回其内容

3.permanent

# 将 /old 开头的请求重定向到 /new 路径
location /old {
    rewrite ^/old/(.*)$ /new/$1 permanent;
}

Ⅲ,if指令

一. 基本语法

if (condition) {
    # 配置指令
}
------
if (条件){
#满足条件执行的内容
}

二.使用案例

1、网站只准许GET,POST,HEAD3种请求方法,其他访问禁止访问

server {
  listen 80;
  server_name daemon.com;
  root /app/code/rewrite ;
  if ( $request_method  !~ "GET|POST"  ) {
     return 403; #这里可以使用405状态码,405表示使用的请求方法不被网站准许或支
持.
  }
  location / {
    index index.html;
  }
 }

2.其他案例

###变量匹配
if ($http_user_agent ~* "(android|iphone)") {
    # 匹配移动设备User-Agent
}

if ($request_method != POST) {
    # 非POST请求处理
}

###参数验证
if ($arg_token != "secret123") {
    return 403;
}

Ⅳ、set指令

一. 基本语法

set $variable value;
set $变量名字 值
例如 set $name 小明

二、案例使用

案例1,输出ip

server {
  listen 80;
  server_name daemon.com;
  set $url $http_host$request_uri;
  return 200 "$url\n";
 }
输出200的状态包括host头和请求地址

案例2.设置网站是否为维护状态:如果维护状态:返回503状态码,否则正常访 问.设置503页面.

server { 
  listen 80;
  server_name rewrite.oldboylinux.cn;
  root /app/code/rewrite;
  set $flag 0;
  #include conf.d/rewrite-status.var;也可以用include把文件引用进来
  if ( $flag = 1  ) {
    return 503;
  }
  location / {
    index index.html;
  }
 }

Ⅴ,综合案例

示例1:多条件重定向

“`bash
location / {
set $redirect 0;

# 条件1:旧域名重定向
if ($host = "old.example.com") {
    set $redirect 1;
}

# 条件2:HTTP重定向到HTTPS
if ($scheme = "http") {
    set $redirect "${redirect}1";
}

# 条件3:特定路径重定向
if ($uri ~* "^/outdated") {
    set $redirect "${redirect}1";
}

# 执行重定向
if ($redirect = 111) {
    return 301 https://new.example.com/updated$uri;
}
if ($redirect = 11) {
    return 301 https://$host$uri;
}
if ($redirect = 1) {
    return 301 https://new.example.com$uri;
}

}

文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇