插件窝 干货文章 Nginx中location匹配及rewrite重写跳转的方法

Nginx中location匹配及rewrite重写跳转的方法

匹配 location rewrite Nginx 1033    来源:    2025-04-22

Nginx中location匹配及rewrite重写跳转详解

location匹配规则

Nginx的location指令用于匹配请求URI,语法如下:

location [modifier] pattern {
    ...
}

匹配修饰符(modifier)

  1. 无修饰符:前缀匹配(区分大小写)

    location /images/ {
       # 匹配以/images/开头的URI
    }
    
  2. =:精确匹配

    location = /logo.png {
       # 只匹配/logo.png
    }
    
  3. ~:正则匹配(区分大小写)

    location ~ \.php$ {
       # 匹配以.php结尾的URI,区分大小写
    }
    
  4. ~*:正则匹配(不区分大小写)

    location ~* \.(jpg|jpeg|png)$ {
       # 匹配图片文件,不区分大小写
    }
    
  5. ^~:优先前缀匹配(匹配后不再检查正则)

    location ^~ /static/ {
       # 匹配以/static/开头的URI,优先于正则匹配
    }
    

匹配优先级

  1. 精确匹配 =
  2. 优先前缀匹配 ^~
  3. 正则匹配 ~~*(按配置文件中出现的顺序)
  4. 普通前缀匹配

rewrite重写规则

rewrite指令用于修改请求URI,语法:

rewrite regex replacement [flag];

常用flag

  1. last:停止处理当前rewrite指令集,用新URI重新匹配location
  2. break:停止处理当前rewrite指令集,继续执行后续指令
  3. redirect:返回302临时重定向
  4. permanent:返回301永久重定向

示例

  1. 简单的重写:

    rewrite ^/oldpath$ /newpath permanent;
    
  2. 带参数的重写:

    rewrite ^/product/(\d+)$ /item.php?id=$1? last;
    
  3. 条件重写:

    if ($host != 'www.example.com') {
       rewrite ^/(.*)$ http://www.example.com/$1 permanent;
    }
    

综合应用示例

server {
    listen 80;
    server_name example.com;

    # 精确匹配首页
    location = / {
        rewrite ^ /index.php last;
    }

    # 静态文件处理
    location ^~ /static/ {
        root /var/www/html;
        expires 30d;
    }

    # PHP文件处理
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
    }

    # 旧URL重定向
    location /old/ {
        rewrite ^/old/(.*)$ /new/$1 permanent;
    }

    # 商品详情页重写
    location /product {
        rewrite ^/product/(\d+)$ /detail.php?id=$1 last;
    }

    # 404处理
    location / {
        try_files $uri $uri/ =404;
    }
}

调试技巧

  1. 使用rewrite_log on;开启重写日志(需要设置error_log级别为notice)
  2. 使用return 200 "message";测试匹配情况
  3. 使用curl测试重定向: bash curl -I http://example.com/old/path

注意事项

  1. 避免过度使用rewrite,可能影响性能
  2. 注意rewrite规则顺序,Nginx按顺序匹配
  3. 使用$1, $2等捕获组时注意正则表达式的括号
  4. 永久重定向(301)会被浏览器缓存,开发时慎用

通过合理配置location和rewrite规则,可以实现灵活的URL路由、重定向和伪静态等功能。