0
点赞
收藏
分享

微信扫一扫

nginx ngx_http_rewrite_module模块 rewrite 指令介绍:重写 URL


rewrite 指令是由 Nginx 的 ngx_http_rewrite_module 模块提供的。这个模块用于在处理请求时根据预定义的规则重写 URL。ngx_http_rewrite_module 是 Nginx 的核心模块之一,通常默认编译在 Nginx 中,无需额外安装。

模块功能

ngx_http_rewrite_module 提供了以下主要功能:

  1. URL 重写:根据正则表达式匹配和替换规则,将请求的 URL 重写为另一个 URL。
  2. 条件判断:使用 if 指令进行条件判断,根据不同的条件执行不同的重写规则。
  3. 重定向:可以将请求重定向到另一个 URL,支持临时重定向(HTTP 302)和永久重定向(HTTP 301)。
  4. 变量设置:可以在重写规则中设置和使用变量。

常用指令

1. rewrite

用于根据正则表达式匹配和替换 URL。

  • 语法

rewrite regex replacement [flag];

  • 参数
  • regex:正则表达式,用于匹配请求的 URL。
  • replacement:替换后的 URL。
  • flag:可选标志,用于控制重写行为。常见的标志有:
  • last:停止当前的 rewrite 规则集,开始下一个阶段的处理。
  • break:停止当前的 rewrite 规则集,不再进行后续的 rewrite 处理。
  • redirect:返回临时重定向(HTTP 302)。
  • permanent:返回永久重定向(HTTP 301)。
2. if

用于条件判断。

  • 语法

if (condition) {
    ...
}

  • 参数
  • condition:条件表达式,可以是变量、字符串比较、文件/目录存在性检查等。
3. set

用于设置变量。

  • 语法

set $variable value;

  • 参数
  • $variable:要设置的变量名。
  • value:变量的值,可以是静态字符串或变量表达式。

示例配置

以下是一个完整的 Nginx 配置示例,展示了 rewrite 指令和其他相关指令的用法:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
    client_max_body_size 10m;

    server {
        listen 80;
        server_name example.com;

        # 内部重写
        location /old-path {
            rewrite ^/old-path(.*)$ /new-path$1 last;
        }

        location /new-path {
            # 处理新路径的逻辑
        }

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

        location /redirect-new {
            # 处理新路径的逻辑
        }

        # 使用变量
        location /blog/post/ {
            rewrite ^/blog/post/(.*)$ /article/$1 last;
        }

        location /article/ {
            # 处理文章的逻辑
        }

        # 条件重写
        location / {
            if ($http_host = "example.com") {
                rewrite ^/old-site(.*)$ /new-site$1 permanent;
            }

            if (!-e $request_filename) {
                rewrite ^ /404.html break;
            }
        }

        location = /404.html {
            # 处理 404 页面的逻辑
        }
    }
}

检查模块是否启用

你可以通过以下命令检查 Nginx 是否编译了 ngx_http_rewrite_module 模块:

nginx -V 2>&1 | grep -- '--with-http_rewrite_module'

如果输出中包含 --with-http_rewrite_module,则表示该模块已启用。


举报

相关推荐

0 条评论