NGINX 301 redirect using query argument value

ぃ、小莉子 提交于 2021-02-08 11:15:25

问题


I want to redirect example.com/?lang=en to example.com/en/.

I am using Python Django and my server running Plesk / Nginx.

I try to redirect on my webpage like this. But it's don't work;

rewrite ^/?lang=en$ /en/ redirect;

But if i remove question mark rewrite is worked.

I tried many methods but I couldn't find a solution.

Thank You.


回答1:


The most simple is

if ($arg_lang = en) {
    return 301 /en$uri;
}

However if you'd have any other query arguments, they would lost with this redirection rule. To preserve all the other query arguments you can do the following:

if ($args ~ (.*)(^|&)lang=en(\2|$)&?(.*)) {
    set $args $1$3$4;
    return 301 /en$uri$is_args$args;
}

To support several languages the first solution came to mind is

if ($args ~ (.*)(^|&)lang=([^&]*)(\2|$)&?(.*)) {
    set $args $1$4$5;
    return 301 /$3$uri$is_args$args;
}

However if you'd have some malformed lang query argument value it would lead to redirection to non-existent page. To filter lang values for supported languages only you can use the map directive:

map $arg_lang $prefix {
    en    /en;
    de    /de;
    ...
    # if none matched, value of $prefix variable would be an empty string
}
map $args $stripped_args {
    # remove "lang" query argument if exists
    ~(.*)(^|&)lang=[^&]*(\2|$)&?(.*)  $1$3$4;
    default                           $args;
}
server {
    ...
    if ($prefix) {
        set $args $stripped_args;
        return 301 $prefix$uri$is_args$args;
    }
    ...
}

If your URI language prefix is the same as the lang query argument value (or can be derived from it through some regular expression), the first map block could be simplified:

map $arg_lang $prefix {
    ~^(en|de|...)$    /$1;
}

Update

As OP states, there could be a caveat when we've got a request like example.com/de/some/path/?lang=en which would be redirected to non-existent page example.com/en/de/some/path/. To avoid it we could define additional map block and strip the language prefix from the URI:

map $arg_lang $prefix {
    ~^(en|de|...)$    /$1;
}
map $args $stripped_args {
    # remove "lang" query argument if exists
    ~(.*)(^|&)lang=[^&]*(\2|$)&?(.*)  $1$3$4;
    default                           $args;
}
map $uri $stripped_uri {
    # remove language prefix from URI if one exists
    ~^/(en|de|...)(/.*)$  $2;
    default               $uri;
}
server {
    ...
    if ($prefix) {
        set $args $stripped_args;
        return 301 $prefix$stripped_uri$is_args$args;
    }
    ...
}


来源:https://stackoverflow.com/questions/62656217/nginx-301-redirect-using-query-argument-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!