Home > Software engineering >  Nginx regex to lower any uri expect files
Nginx regex to lower any uri expect files

Time:08-29

I am trying to write a regex that redirects any uppercase url to lowercase but it should exclude files.

location ~ ^[A-Z]?(?!.*(\.)).*$ {
    rewrite_by_lua_block {
      ngx.redirect(string.lower(ngx.var.uri), 301);
    }
  }

I tried different combinations but none working as expected, Please suggest any regex that should act on uri that contain Uppercase letter but ignores if it ends to be a file.

Examples:

https://wwwalls.com/category/Entertainment [match]
https://wwwalls.com/images/test.Png [dont match]

CodePudding user response:

Have it like this:

location ~ ^[^.]*[A-Z][^.]*$ {
   rewrite_by_lua_block {
      ngx.redirect(string.lower(ngx.var.uri), 301);
   }
}

Regex ^[^.]*[A-Z][^.]*$ will match any URI that has no DOT anywhere and must have at least one uppercase letter.

  • Related