Force URLs to lowercase, especially important for SEO to avoid duplicate content penalties. Even more so on Windows-based servers, which are case-insensitive by default. It is imperative for good architectural SEO to standardize on lowercase urls and redirect mixed-case urls to them accordingly.
Rewrite by Lua
Lua must be installed and available in NGINX. If not, it is typically bundled with the nginx-extras package from most installers. For example, on Ubuntu:
apt-get install nginx-extras
Instead of the standard nginx package.
Once Lua is available, add the following location block:
server {
# ...
location ~ [A-Z] {
rewrite_by_lua_block {
ngx.redirect(string.lower(ngx.var.uri), 301);
}
}
# ...
}
The Lua method above is preferred over the embedded Perl version below as it is a bit more performant. For SEO purposes, the redirect should be Permanent (301).
Rewrite with Perl
Perl must be installed and available in NGINX. If not, it is typically bundled with the nginx-extras package as described above under Rewrite by Lua.
Once Perl is available, in nginx.conf add the following code within the http { } section:
http {
perl_set $uri_lowercase 'sub {
my $r = shift;
my $uri = $r->uri;
$uri =~ s/\R//; # replace all newline characters
$uri = lc($uri);
return $uri;
}';
}
Once that is done, you can then add the location block below to the appropriate site config file:
server {
# ...
location ~ [A-Z] {
rewrite ^(.*)$ $scheme://$host$uri_lowercase permanent;
}
# ...
}
For SEO purposes, this redirect should be Permanent (301).
Special thanks to Martin Cambal for an improvement in the Perl version that addresses CRLF vulnerabilities. See more here: https://stackoverflow.com/a/68054489