lolly/docs/config/rewriting/rewrite-rules.conf
xfy 6543422281 docs: 添加 Nginx 配置和 Lua 脚本示例文档
- config: 反向代理、缓存、负载均衡、安全、SSL 等配置模板
- lua: API 网关、认证、动态路由、限流、WebSocket 等脚本示例

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 17:59:22 +08:00

107 lines
2.9 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ============================================================
# Nginx URL 重写规则配置示例
# ============================================================
#
# 功能说明:
# - URL 重写和重定向
# - 正则表达式匹配
# - flag 参数控制行为
#
# Lolly 对应配置:
# server:
# rewrite:
# - pattern: "^/old/(.*)$"
# replacement: "/new/$1"
# flag: "last" # 可选值: last, redirect, permanent, break
# ============================================================
http {
server {
listen 80;
server_name rewrite.example.com;
# rewrite 指令语法
# rewrite regex replacement [flag];
# Lolly 对应: rewrite 配置列表
# 永久重定向301
# Lolly 对应: flag: "permanent"
rewrite ^/old-page$ /new-page permanent;
rewrite ^/old/(.*)$ /new/$1 permanent;
# 临时重定向302
# Lolly 对应: flag: "redirect"
rewrite ^/download/(.*)$ /files/$1 redirect;
# 内部重写(不改变 URL
# Lolly 对应: flag: "last"
rewrite ^/api/v1/(.*)$ /api/$1 last;
rewrite ^/user/(.*)$ /profile/$1 last;
# break - 停止处理后续规则
rewrite ^/static/(.*)$ /assets/$1 break;
# 带参数的重写
# $1, $2 等捕获组引用
rewrite ^/category/([0-9]+)/([0-9]+)$ /products?cat=$1&page=$2 last;
# 不追加原参数(结尾加 ?
rewrite ^/search/(.*)$ /query?term=$1? last;
# 基于条件的重写
if ($request_method = POST) {
rewrite ^/api$ /api/handler last;
}
# 移除 .php 扩展名
rewrite ^/(.*)\.php$ /$1 last;
location / {
root /var/www/html;
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass http://backend:8080;
}
}
}
# rewrite flag 说明:
#
# 1. last:
# - 停止当前 rewrite 规则处理
# - 开始搜索新 location重新进入处理循环
# - 常用于内部重写
# - Lolly 对应: flag: "last"
#
# 2. break:
# - 停止当前 rewrite 规则处理
# - 继续在当前 location 中处理
# - 不会重新搜索 location
# - Lolly 对应: flag: "break"
#
# 3. redirect:
# - 返回 302 临时重定向
# - 客户端 URL 改变
# - Lolly 对应: flag: "redirect"
#
# 4. permanent:
# - 返回 301 永久重定向
# - 搜索引擎会更新索引
# - Lolly 对应: flag: "permanent"
#
# 参数处理说明:
#
# 1. 默认行为:
# replacement 中不包含参数时,原请求参数自动追加
# rewrite ^/a$ /b; # /a?x=1 -> /b?x=1
#
# 2. 新参数:
# replacement 包含参数时,原参数追加到新参数后
# rewrite ^/a$ /b?y=2; # /a?x=1 -> /b?y=2&x=1
#
# 3. 不追加原参数:
# replacement 以 ? 结尾时不追加原参数
# rewrite ^/a$ /b?; # /a?x=1 -> /b
# rewrite ^/a$ /b?y=2?; # /a?x=1 -> /b?y=2