'ingress-nginx host redirect in server snippet doesnt work

I'm using wildcard subdomain in the ingress and need to redirect any request that contains subdomain with www to non-www i.e.: www.randomsubdomain.domain.com to randomsubdomain.domain.com

For this reason I tried to add server snippet to the ingress but it has no effect at all, I have tested my regular expression and it fits my problem but seem to be ignored by my ingress:

    nginx.ingress.kubernetes.io/server-snippet: |
        if ($host ~* "^(www\.)([0-9a-z]+\.domain\.com)$") {
          return 301 https://$2$request_uri;
        }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source