温馨提示×

详解常用的nginx rewrite重写规则

小云
107
2023-08-14 13:25:20
栏目: 编程语言

在Nginx中,rewrite指令用于重写URL。它允许用户修改请求URI、查询参数以及HTTP请求方法。

以下是常用的Nginx rewrite重写规则:

  1. 重写URI:
  • 重写到固定URI:rewrite ^/old-uri$ /new-uri last;

  • 重写到带变量的URI:rewrite ^/product/(\d+)$ /product?id=$1 last;

  1. 重写查询参数:
  • 添加查询参数:rewrite ^/product$ /product?id=123 last;

  • 修改查询参数:rewrite ^/product?id=(\d+)$ /product?id=$1&category=1 last;

  • 移除查询参数:rewrite ^/product?id=(\d+)&category=1$ /product?id=$1 last;

  1. 重写HTTP请求方法:
  • 将GET请求重写为POST请求:if ($request_method = GET) { rewrite ^/(.*)$ /$1 break; proxy_set_header X-HTTP-Method-Override POST; }
  1. 重定向:
  • 临时重定向:rewrite ^/old-uri$ /new-uri redirect;

  • 永久重定向:rewrite ^/old-uri$ /new-uri permanent;

  1. 条件判断:
  • 只对指定域名进行重写:if ($host = example.com) { rewrite ^/(.*)$ /$1 break; }

需要注意的是,rewrite指令在每个请求处理阶段都会被执行,因此应该避免使用过多的rewrite规则,以免对性能产生不利影响。另外,为了避免死循环,rewrite规则应该设计成能够在有限次数内匹配成功。

0