插件窝 干货文章 Nginx怎么配置location与rewrite规则

Nginx怎么配置location与rewrite规则

匹配 Location Rewrite Nginx 659    来源:    2025-04-23

Nginx Location与Rewrite规则配置指南

Location配置

Location指令用于匹配请求URI,语法如下:

location [modifier] pattern {
    # 配置指令
}

匹配修饰符

  1. 无修饰符 - 前缀匹配

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

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

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

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

    location ^~ /static/ {
       # 匹配以/static/开头的URI,不检查后续的正则location
    }
    

匹配优先级

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

Rewrite配置

Rewrite指令用于重写URL,语法如下:

rewrite regex replacement [flag];

常用flags

  • last - 停止处理当前rewrite规则集,并用重写后的URI继续匹配location
  • break - 停止处理当前rewrite规则集
  • redirect - 返回302临时重定向
  • permanent - 返回301永久重定向

示例

  1. 简单重写:

    rewrite ^/oldpath$ /newpath permanent;
    
  2. 捕获组使用:

    rewrite ^/user/(.*)$ /profile?username=$1 last;
    
  3. 文件不存在时重写:

    if (!-f $request_filename) {
       rewrite ^/(.*)$ /index.php?q=$1 last;
    }
    

综合示例

server {
    listen 80;
    server_name example.com;

    # 静态文件处理
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        access_log off;
    }

    # PHP处理
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # 重写规则 - 美化URL
    location / {
        try_files $uri $uri/ @rewrite;
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1 last;
    }

    # 特定路径重定向
    location = /old-page {
        rewrite ^ /new-page permanent;
    }
}

注意事项

  1. 避免过度使用rewrite,可能会影响性能
  2. 正则表达式要尽量精确,避免过于宽泛的匹配
  3. 测试配置后记得重载Nginx:nginx -s reload
  4. 使用rewrite_log on;可以开启重写日志便于调试

希望这些配置示例能帮助你更好地理解和使用Nginx的location和rewrite规则。