跳转至

internal-redirect: 内部重定向到指定的 URI

安装

您可以在任何基于 RHEL 的发行版中安装此模块,包括但不限于:

  • RedHat Enterprise Linux 7、8、9 和 10
  • CentOS 7、8、9
  • AlmaLinux 8、9
  • Rocky Linux 8、9
  • Amazon Linux 2 和 Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install nginx-module-internal-redirect
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install nginx-module-internal-redirect

通过在 /etc/nginx/nginx.conf 的顶部添加以下内容来启用模块:

load_module modules/ngx_http_internal_redirect_module.so;

本文档描述了 nginx-module-internal-redirect v0.1.0,于 2026 年 1 月 06 日发布。


server {
    listen 127.0.0.1:80;
    server_name localhost;

    location /old {
        internal_redirect -i ^/old(.+) /new$1 phase=preaccess;
    }

    location /new {
        return 200 'current uri is: $uri';
    }
}

指令

internal_redirect

语法: internal_redirect [-i] pattern replacement [phase=] [flag=] [if= | if!=]

默认值: -

上下文: http, server, location

设置请求的内部重定向的新 URI。也可以使用命名位置代替 URI。替换值可以包含变量。如果 uri 值为空,则不会进行重定向。发生内部重定向后,请求 URI 将被更改,请求将返回到 NGX_HTTP_SERVER_REWRITE_PHASE (server_rewrite) 阶段。请求将继续使用服务器的默认位置。稍后在 NGX_HTTP_FIND_CONFIG_PHASE (find_config) 阶段,将根据新的请求 URI 选择一个新位置。

有关 nginx 请求阶段的更多信息,请参阅 Development guide#http_phases

可选的 -i 参数指定应执行不区分大小写的正则表达式匹配。

可选的 phase= 参数用于指示此规则生效的阶段。可能的值为 preaccess、access、precontent 和 content。每个阶段的规则将在执行内部重定向之前完全执行。默认值为 preaccess。

可选的 flag= 参数用于在评估规则后执行额外的操作。此参数的值可以是以下之一: * break 在此阶段停止处理当前规则集,并立即执行内部重定向; * status_301 返回 301 代码的重定向。 * status_302 返回 302 代码的重定向。 * status_303 返回 303 代码的重定向。 * status_307 返回 307 代码的重定向。 * status_308 返回 308 代码的重定向。

if 参数启用条件重定向。如果条件评估为“0”或空字符串,请求将不会被重定向。您还可以使用 if!= 的形式进行否定判断。

GitHub

您可以在 nginx-module-internal-redirect 的 GitHub 仓库 中找到此模块的其他配置提示和文档。