首页 > 解决方案 > 是否可以在 Nginx 配置中使用带有重定向代码的变量?

问题描述

在我的 Nginx 配置中,我有这样的重定向规则:

map $uri $target {
    '/test123' 'https://www.somedomain.com/test456';
}
map $uri $target_code {
    '/test123' 301;
}
server {
    listen 80 default;

    if ($target_code = 301) {
        return 301 $target;
    }
    if ($target_code = 302) {
        return 302 $target;
    }
}

它运作良好。但是关于如果是邪恶的

我想做这样的声明:

server {
    listen 80 default;

    return $target_code $target;
}

但是在重启过程中,Nginx 返回错误nginx: [emerg] invalid return code "$target_code" in /etc/nginx/nginx.conf

有没有可能以这种方式使用变量?或者也许是没有任何 if 语句的其他方法?

标签: nginxnginx-config

解决方案


据我所知,这是不可能的。以下是代码的相关部分:

    ret->status = ngx_atoi(p, value[1].len);

    if (ret->status == (uintptr_t) NGX_ERROR) {

        if (cf->args->nelts == 2
            && (ngx_strncmp(p, "http://", sizeof("http://") - 1) == 0
                || ngx_strncmp(p, "https://", sizeof("https://") - 1) == 0
                || ngx_strncmp(p, "$scheme", sizeof("$scheme") - 1) == 0))
        {
            ret->status = NGX_HTTP_MOVED_TEMPORARILY;
            v = &value[1];

        } else {
            ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                               "invalid return code \"%V\"", &value[1]);
            return NGX_CONF_ERROR;
        }

首先它尝试将第一个参数转换为整数。如果失败,它会检查这是否是一个 URL。如果没有,它会因错误而退出。


推荐阅读