Nginx Rewrite Rule for replacing space/whitespace with Hyphen and convert URL to lowercase

How can I convert all my URLs to lower case and replace space " " with - hyphen in NGINX ??


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.

Need Your Help

Why cvFindContours() method doesn't detect Contours correctly in javacv?

java opencv javacv

I went through many questions in StackOverflow and able to develop small program to detect squares and rectangles correctly. This is my sample code

Retrieving and storing data from pls file in PHP

php regex stream store

I need to create a series of regular expressions to get data out of a pls file in PHP (a language I've only just started learning).