插件窝 干货文章 Nginx如何实现基于请求URI的请求重写配置

Nginx如何实现基于请求URI的请求重写配置

重写 rewrite Nginx 指令 146    来源:    2025-04-10

Nginx基于请求URI的请求重写配置

Nginx提供了强大的URL重写功能,主要通过rewrite指令和location块来实现基于请求URI的请求重写。以下是详细的配置方法和示例:

基本rewrite指令语法

rewrite regex replacement [flag];
  • regex: 正则表达式匹配原始URI
  • replacement: 替换后的URI
  • flag: 可选参数,控制重写行为

常用flag选项

  • last: 停止处理当前rewrite指令集,并用重写后的URI重新搜索location
  • break: 停止处理当前rewrite指令集
  • redirect: 返回302临时重定向
  • permanent: 返回301永久重定向

常见配置示例

1. 基本URI重写

location /old-path/ {
    rewrite ^/old-path/(.*)$ /new-path/$1 last;
}

2. 带条件的重写

if ($request_uri ~* "^/product/([0-9]+)") {
    rewrite ^/product/([0-9]+)$ /products?id=$1? last;
}

3. 文件扩展名重写

rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;

4. 去除或添加尾部斜杠

# 确保URI以斜杠结尾
rewrite ^([^.]*[^/])$ $1/ permanent;

# 去除尾部斜杠
rewrite ^/(.*)/$ /$1 permanent;

5. 多级目录重写

rewrite ^/category/(.+)/subcategory/(.+)$ /products?cat=$1&subcat=$2? last;

6. 重定向旧页面到新位置

location /old-page.html {
    rewrite ^/old-page.html$ /new-page.html permanent;
}

最佳实践

  1. 优先使用location块:相比if条件,location块更高效且更安全
  2. 避免过多重写:每个重写都会带来性能开销
  3. 合理使用flag
    • 内部重写使用lastbreak
    • 外部重定向使用permanentredirect
  4. 测试正则表达式:确保正则表达式准确匹配预期URI
  5. 考虑使用map指令:对于复杂的重写规则,map指令可能更清晰

调试技巧

  1. 启用rewrite日志:
rewrite_log on;
error_log /var/log/nginx/error.log notice;
  1. 使用return指令测试模式匹配:
location /test-rewrite {
    return 200 "Matched: $request_uri";
}

通过合理配置这些重写规则,你可以实现复杂的URL转换逻辑,同时保持网站的SEO友好性和用户体验。