微信公众号
扫描关注微信公众号
博客大厅

什么是 Nginx 的 rewrite 规则?举例说明

原创 来源:博客站 阅读 0 今天 07:53:10 听全文

Nginx 的 rewrite 规则 用于重写(修改)客户端请求的 URI,实现 URL 重定向、路径映射、SEO 优化等功能。它通过正则表达式匹配和替换规则,动态修改请求的路径,而无需实际改变服务器文件结构。以下是详细说明和实际示例:


1. rewrite 指令语法

rewrite regex replacement [flag];
  • regex:正则表达式匹配原始 URI。
  • replacement:替换后的新 URI。
  • flag:可选标志,控制重写行为(如重定向方式)。

常用 flag

标志 作用
last 重写后重新匹配后续的 location 规则(常用)。
break 重写后立即停止处理当前规则集,不再匹配其他规则。
redirect 返回 302 临时重定向(浏览器地址栏会变)。
permanent 返回 301 永久重定向(SEO 友好,浏览器会缓存)。

2. 常见场景示例

(1) 基础路径重写

场景:将 /old-path 重写到 /new-path,不改变浏览器地址。

location /old-path {
    rewrite ^/old-path$ /new-path last;
}
  • 效果
    http://example.com/old-path → 内部处理为 /new-path

(2) 强制 HTTPS 重定向

场景:将所有 HTTP 请求重定向到 HTTPS。

server {
    listen 80;
    server_name example.com;
    rewrite ^(.*)$ https://$host$1 permanent;  # 301 永久重定向
}
  • 效果
    http://example.comhttps://example.com

(3) 动态 URL 美化

场景:将 /product/123 转换为后台实际的 /product?id=123

location /product {
    rewrite ^/product/(d+)$ /product?id=$1 break;  # 隐藏参数
}
  • 效果
    http://example.com/product/123 → 内部处理为 /product?id=123

(4) 移除或添加后缀

场景:移除 .html 后缀(SEO 友好)。

location / {
    rewrite ^/(.*).html$ /$1 last;  # /about.html → /about
}

(5) 多级路径合并

场景:将 /blog/2023/post-title 转换为 /blog.php?year=2023&title=post-title

rewrite ^/blog/(d+)/(.+)$ /blog.php?year=$1&title=$2 last;
  • 效果
    http://example.com/blog/2023/hello-world/blog.php?year=2023&title=hello-world

(6) 域名重定向

场景:将旧域名重定向到新域名。

server {
    listen 80;
    server_name old.com;
    rewrite ^(.*)$ http://new.com$1 permanent;
}

3. 高级技巧

(1) 条件判断

结合 if 实现条件重写:

if ($request_uri ~* "/search/(.*)") {
    rewrite ^ /search.php?q=$1 last;
}

(2) 防止重复重写

使用 break 避免循环:

location /download/ {
    rewrite ^/download/(.*)$ /files/$1 break;  # 只执行一次
}

(3) 保留查询参数

自动保留原始 URL 中的 ? 参数:

rewrite ^/old-path$ /new-path?$args last;

4. 完整配置示例

server {
    listen 80;
    server_name example.com;

    # 案例1:强制 www → 非 www(SEO统一)
    rewrite ^/(.*)$ http://example.com/$1 permanent;

    # 案例2:隐藏.php扩展
    location / {
        rewrite ^/([^/]+).php$ /$1 last;
    }

    # 案例3:API版本控制
    location /api {
        rewrite ^/api/v1/(.*)$ /api.php?version=1&path=$1 break;
    }

    # 案例4:处理静态资源缓存破坏(带hash的文件)
    location ~* ^/.+.(w+).(css|js)$ {
        rewrite ^/(.+).w+.(css|js)$ /$1.$2 last;
    }
}

5. 验证与调试

  1. 检查语法
    sudo nginx -t
    
  2. 查看重写日志(调试时启用):
    rewrite_log on;  # 在 error_log 中记录重写过程
    error_log /var/log/nginx/error.log notice;
    
  3. 使用 curl 测试
    curl -I http://example.com/old-path  # 观察 Location 头
    

注意事项

  • 避免循环重写:规则可能相互触发,导致无限循环(如 rewrite /a /b last; rewrite /b /a last;)。
  • 性能影响:复杂的正则表达式会增加 CPU 开销。
  • 优先级rewritelocation 块中执行,顺序很重要。

通过灵活使用 rewrite 规则,可以实现 URL 美化、旧链接兼容、多域名整合等需求,同时保持对搜索引擎友好。

学在每日,进无止境!更多精彩内容请关注微信公众号。
原文出处: 内容由AI生成仅供参考,请勿使用于商业用途。如若转载请注明原文及出处。
出处地址:http://www.07sucai.com/tech/971.html
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。
>