插件窝 干货文章 nginx怎么配置url重定向

nginx怎么配置url重定向

定向 server example return 899    来源:    2025-04-27

Nginx URL重定向配置指南

URL重定向是网站维护和SEO优化中常见的需求,Nginx提供了多种方式来实现URL重定向。以下是几种常见的配置方法:

1. 基础重定向(301永久重定向)

server {
    listen 80;
    server_name example.com;

    # 单个URL重定向
    location = /old-url {
        return 301 https://example.com/new-url;
    }

    # 目录重定向
    location /old-dir/ {
        return 301 https://example.com/new-dir/;
    }
}

2. 域名重定向

server {
    listen 80;
    server_name old-domain.com www.old-domain.com;
    return 301 https://new-domain.com$request_uri;
}

3. HTTP到HTTPS重定向

server {
    listen 80;
    server_name example.com;
    return 301 https://example.com$request_uri;
}

4. 非www到www重定向(或反之)

# 非www重定向到www
server {
    listen 80;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

# www重定向到非www
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

5. 使用rewrite规则实现复杂重定向

server {
    listen 80;
    server_name example.com;

    # 带参数的重定向
    rewrite ^/product/([0-9]+)$ /products/$1 permanent;

    # 条件重定向
    if ($request_uri ~* "^/old-path/(.*)") {
        rewrite ^ /new-path/$1 permanent;
    }

    # 文件扩展名重定向
    rewrite ^(.*)\.htm$ $1.html permanent;
}

6. 保留查询字符串的重定向

server {
    listen 80;
    server_name example.com;

    location /old-page {
        return 301 /new-page$is_args$args;
    }
}

7. 基于变量的重定向

map $http_user_agent $redirect_uri {
    default        "";
    "~*Mobile"     "/mobile";
}

server {
    listen 80;
    server_name example.com;

    if ($redirect_uri) {
        return 301 $redirect_uri;
    }
}

注意事项

  1. 301 vs 302

    • 301是永久重定向(SEO友好)
    • 302是临时重定向(不传递SEO权重)
  2. 性能考虑

    • 尽量使用return而不是rewrite,因为return更高效
    • 避免过多的重定向链
  3. 测试

    • 配置完成后使用nginx -t测试配置是否正确
    • 使用curl检查重定向是否按预期工作:curl -I http://example.com/old-url
  4. 缓存

    • 浏览器会缓存301重定向,清除缓存或使用隐私模式测试

希望这些配置示例能帮助你实现所需的URL重定向功能。根据你的具体需求选择合适的重定向方式。