# 变量与内置指令

URL: https://caijiao.org/nginx/variables
Source: docs/nginx/variables.md
Description: 本节介绍 Nginx 配置文件中的变量与内置指令，包括常用内置变量、条件判断、rewrite、proxy_pass 等指令，帮助你灵活控制请求处理与响应逻辑。

Nginx 支持丰富的内置变量与指令，通过这些工具可以实现动态请求处理、条件判断和高级路由功能。

## 一、常用内置变量

| 变量 | 说明 |
|------|------|
| `$host` | 客户端请求的 Host |
| `$uri` | 请求的 URI |
| `$document_root` | 当前请求根目录 |
| `$remote_addr` | 客户端 IP 地址 |
| `$request_method` | 请求方法，如 GET、POST |
| `$query_string` | 请求的查询参数 |
| `$status` | 响应状态码 |

### 使用示例

```nginx
server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/html;
        index index.html;
        add_header X-Client-IP $remote_addr;
    }
}
````

## 二、常用内置指令

### 1. rewrite

用于重写 URL 或跳转：

```nginx
location /old-path/ {
    rewrite ^/old-path/(.*)$ /new-path/$1 permanent;
}
```

### 2. return

快速返回状态码或重定向：

```nginx
location / {
    return 301 https://example.com$request_uri;
}
```

### 3. set

定义自定义变量：

```nginx
set $my_var "Hello Nginx";
```

### 4. if 条件判断

```nginx
if ($request_method = POST) {
    return 405;
}
```

### 5. proxy_pass

反向代理指令，用于将请求转发到后端服务：

```nginx
location /api/ {
    proxy_pass http://127.0.0.1:8080/;
}
```

## 三、使用建议

1. 尽量减少复杂的 `if` 嵌套，可用 map 或 try_files 替代
2. 熟悉常用内置变量，可灵活处理请求头、请求路径与客户端信息
3. 配合 rewrite、return、proxy_pass 指令，实现动态路由和反向代理

---

掌握 Nginx 的变量与内置指令，可以让你对请求处理逻辑进行精细控制，是配置高性能 Web 服务的重要技能。
