1

all, I am new to nginx and server, I have trouble dealing with nginx rewrite rules. I want to lowercase all urls and remove some string. I have an eCommerce website, the current URL structures are like these:(to avoid being recognized as links by stackoverflow, I add a space between http and : on purpose)

product page: http ://www.example.com/Some-Product-pd123456.html
product category: http ://www.example.com/Product-Cat-pl12345.html
page a: http ://www.example.com/About-Us.html
page b: http ://www.example.com/Contactus.html

So, what I want to achieve are these:

product page: https ://www.example.com/product/some-product/
product category: https ://www.example.com/category/product-cat/
page a: https ://www.example.com/about-us/
page b: https ://www.example.com/contact-us/

Noted, my website will go from http to https, and I have multiple pages like page a(same pattern) and multiple pages like page b(no pattern). These are so far what I have done:

//product
location ~ ^http:\/\/www\.example\.com\/(.*)-pd\d{6}\.html$ {
    return 301 https://www.example.com/product/$1/;
}

//product category
location ~ ^http:\/\/www\.example\.com\/(.*)-pl\d{5}\.html$ {
    return 301 https://www.example.com/category/$1/;
}
//Page a
location ~ ^http:\/\/www\.example\.com\/(.*)\.html$ {
    return 301 https://www.example.com/$1/;
}

//Page b
location ~ ^http:\/\/www\.example\.com\/Contactus\.html$ {
    return 301 https://www.example.com/contact-us/;
}

So my question is how to lowercase the urls first and then apply those above rules if they are correct, or get them together more nicely and efficiently, for better website speed? Does the location order matters? Thanks for any help.

davidchannal
  • 118
  • 2
  • 8
  • The `http:` is not part of the normalised URI used by `location` and `rewrite` directives (and you do not need to escape the `/` character). Have you considered ignoring case with `location ~*` instead? See [this document](http://nginx.org/en/docs/http/ngx_http_core_module.html#location) for details. – Richard Smith Nov 28 '16 at 09:39
  • Hi, Richard, thanks for your correction and the link you provided helps me a lot. I finally found out a solution, I'll post it as an answer. – davidchannal Nov 30 '16 at 02:49

1 Answers1

0

I answer my own question here.
In order to lower case url, one way to do is using perl. Check out this answer: https://stackoverflow.com/a/11170826/7218247

Then, take product page as example, here is my code in server block:

location ~* "/(.*)-pd\d{6}\.html$" {
        return 301 http://www.example.com/product/$1/;
}

Noted, if you have {} in your regular expression, you need double quotes outside.

Community
  • 1
  • 1
davidchannal
  • 118
  • 2
  • 8