nginx 中 location 结合 rewrite 实现伪静态,核心是用正则匹配真实 url 并重写为后端可识别路径(如 /article/123 → /article.php?id=123),同时对外保持简洁 url;location 先筛选请求范围,rewrite 再改写 uri,常用 last 标志触发重新匹配以交由 php 处理器执行。

Nginx 中 location 块结合 rewrite 实现伪静态,核心是用正则匹配真实 URL,再重写为后端可识别的路径(如 PHP 脚本),同时对外保持简洁友好的 URL 格式。
location 匹配与 rewrite 的配合逻辑
rewrite 指令本身不依赖 location,但通常放在 location 块内,这样能限定作用范围、避免全局误重写。location 先决定哪些请求进入该块,rewrite 再对匹配到的 URI 进行改写。
- location 使用前缀匹配或正则匹配(如
location ~ \.php$或location ^~ /article/)圈定目标请求 - rewrite 规则在该 location 内生效,只处理被这个 location 捕获的请求
- rewrite 后默认发起内部重定向(即 Nginx 自动用新 URI 再次匹配 location),除非加
last、break等标志控制流程
常见伪静态写法示例:文章页 /article/123 → /article.php?id=123
假设希望访问 /article/123 时,实际调用 /article.php?id=123,可这样配置:
location ^~ /article/ {
rewrite ^/article/(\d+)$ /article.php?id=$1 last;
}
说明:
-
^~ /article/是前缀匹配,高效且不参与正则竞争 -
rewrite中的^/article/(\d+)$精确捕获数字 ID -
last表示重写后停止当前 location 处理,用新 URI(/article.php?id=123)重新匹配 location —— 此时应有另一个 location 处理 .php 请求(如 fastcgi_pass)
注意 rewrite 标志对流程的影响
rewrite 后跟的标志决定后续行为,伪静态中常用的是 last 和 break:
-
last:终止当前 location,用新 URI 重新匹配所有 location(适合伪静态,让 PHP 处理器接管) -
break:终止 rewrite,但仍在当前 location 内继续执行后续指令(适合内部路径调整,不触发二次匹配) -
redirect或permanent:返回 302/301 跳转 —— 这是真跳转,不是伪静态,会暴露真实地址
避免循环重写和匹配冲突
伪静态容易因配置不当导致 500 错误(重写循环)或 404(未匹配到后端处理器):
- 确保 rewrite 后的 URI 最终能被某个 location(如
location ~ \.php$)捕获并交给 fastcgi 处理 - 不要在正则 location 中写可能再次匹配自身的 rewrite,例如
location ~ /article/+rewrite /article/(.*) /article/$1可能无限循环 - 优先用
^~前缀匹配做入口,再用 rewrite 转交,比纯正则 location 更清晰可控











