'nginx location to preempt www redirect

I'm trying to support a health check path prior to, or independent from, a www redirect for serving content. My config looks like this:

server {
    listen 8080;

    location /healthz {
        return 200;
    }

    if ( $host !~ ^www\. ) {
        return 302 $scheme://www.$host$request_uri;
    }

    location / {
        try_files $uri $uri/ /index.html;
    }
}

However it'll return the 302 regardless when set like this, and behaves correctly if I nix the if statement. How do I make the /healthz endpoint preempt the www redirect?



Sources

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

Source: Stack Overflow

Solution Source