How i can translate uppercase to lowercase letters in a rewrite rule in nginx web server?

Viewed 30831

I need to translate the address:

www.example.com/TEST in ---> www.example.com/test

7 Answers

I would like to point out that most of Perl answers are vulnerable to CRLF injection.

You should never use nginx's $uri variable in a HTTP redirection. $uri variable is subject to normalization (more info), including:

  • URL encoded characters are decoded
  • Removal of the ? and query string
  • Consecutive / characters are replace by a single /

URL decoding is the reason of CRLF injection vulnerability. The following example url would add a malicious header into your redirect, if you used $uri variable in the redirection.

https://example.org/%0ASet-Cookie:MaliciousHeader:Injected

%0A is decoded to \n\r and nginx will add into headers the following lines:

Location: https://example.org
set-cookie: maliciousheader:injected

The secure Perl redirection requires to replace all newline characters.

perl_set $uri_lowercase 'sub {
    my $r = shift;
    my $uri = $r->uri;
    $uri =~ s/\R//; # replace all newline characters
    $uri = lc($uri);
    return $uri;
}';

Redirect with LUA module.

load_module /usr/lib/nginx/modules/ndk_http_module.so;
load_module /usr/lib/nginx/modules/ngx_http_lua_module.so;

set_by_lua $uri_lowercase "return string.lower(ngx.var.uri)";
location ~[A-Z] {
  return 301 $scheme://$http_host$uri_lowercase$is_args$args;
}
Related