Reputation: 661
How can I convert all my URLs to lower case and replace space " "
with -
hyphen in NGINX ??
Upvotes: 0
Views: 4022
Reputation: 661
I searched few things and I found that perl scripts can help us in this matter. So I am sharing a solution here. How feasible the solution is or is it a best practice, perhaps an NGINX expert can shed some light to it.
First in your nginx.conf
add the following perl script in http block
# Include the perl module
perl_modules perl/lib;
# Define function
perl_set $uri_lowercase 'sub {
my $r = shift;
my $uri = $r->uri;
$uri = lc($uri); # lowercase conversion
# replace space with - hyphen
my $search = " ";
my $replace = "-";
$uri =~ s/$search/$replace/ig;
return $uri;
}';
The reason I wanted to keep in nginx.conf
coz I needed to use this function in multiple vhosts.
Now in your Vhost files write these lines
# In case you want your static content's URL should not be converted to lowercase
# Rewrite skip check jpg uppercase characters. leave it blank no processing is required.
location ~ [A-Z]*\.(jpg|jpeg|gif|png|bmp|ico|flv|swf|css|js) {
}
# now check for uppercase and convert it into lowercase
location ~ [A-Z] {
rewrite ^(.*)$ $scheme://$host$uri_lowercase;
}
# Finally check the whitepaces and replace them
location ~ [\s+] {
rewrite ^(.*)$ $scheme://$host$uri_lowercase;
}
If anybody else can guide me to a better approach I'll be happy to apply that. Hope it helps.
Upvotes: 3