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

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

重写 rewrite Nginx permanent 968    来源:    2025-04-10

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

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

基本重写语法

rewrite regex replacement [flag];
  • regex:正则表达式匹配原始URL
  • replacement:替换后的目标URL
  • flag:可选标志位,控制重写行为

常用flag标志

  • last:停止处理当前重写规则,用新URL重新匹配location
  • break:停止处理当前重写规则,继续处理后续指令
  • redirect:返回302临时重定向
  • permanent:返回301永久重定向

常见配置场景

1. 基本URL重写

server {
    rewrite ^/oldpath$ /newpath permanent;  # 301重定向
    rewrite ^/oldpath2$ /newpath2 last;     # 内部重写
}

2. 带参数重写

rewrite ^/product/([0-9]+)$ /product.php?id=$1 last;

3. 条件重写

if ($request_uri ~* "^/blog/([0-9]{4})/([0-9]{2})/([0-9]+)\.html$") {
    rewrite ^ /blog/$3?year=$1&month=$2 last;
}

4. 文件扩展名重写

rewrite ^(/[^/]+)\.html$ $1.php last;

5. 基于location的重写

location /users/ {
    rewrite ^/users/(.*)$ /user.php?username=$1 break;
}

6. 去除或添加尾部斜杠

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

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

7. 域名重定向

server {
    server_name olddomain.com;
    rewrite ^(.*)$ http://newdomain.com$1 permanent;
}

最佳实践

  1. 性能考虑:尽可能在server块或location块中使用rewrite,避免过多if判断

  2. 测试工具:使用nginx -t测试配置语法是否正确

  3. 缓存清除:重写规则更改后,记得清除浏览器缓存测试

  4. 日志调试:可以开启rewrite日志辅助调试

    rewrite_log on;
    error_log /var/log/nginx/error.log notice;
    
  5. 顺序问题:Nginx按顺序处理rewrite规则,确保规则顺序合理

完整示例

server {
    listen 80;
    server_name example.com;

    # 重定向旧URL
    rewrite ^/old-page$ /new-page permanent;

    # 重写产品URL为友好格式
    rewrite ^/products/([0-9]+)/?$ /product.php?id=$1 last;

    # 去除.php扩展名
    rewrite ^/([^/]+)\.php$ /$1 permanent;

    # 添加尾部斜杠
    rewrite ^([^.]*[^/])$ $1/ permanent;

    # 处理图片请求
    location ~* \.(jpg|jpeg|png|gif)$ {
        rewrite ^/images/(.*)$ /static/$1 break;
    }

    # 其他请求处理
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
}

通过合理配置这些重写规则,你可以实现各种URL美化、重定向和路由功能,提升网站的用户体验和SEO效果。