rewrite – Nginx location match if it is not equal

I have www.example.com/test and I want to write a condition if the requested URL is not equal to / test a rewrite or redirection to www.example.com. The closest I can get is a code below but when I want to use www.example.com/test without / at the end, it redirects me to www.example.com but when I type www.example.com/ test / it works.

location /
fastcgi_param REQUEST_URI $ request_uri;
fastcgi_param HTTPS enabled;

if ($ request_uri! ~ ^ / test /(.*)$)
{return 301 $ scheme: //www.example.com;}

try_files $ uri $ uri / /index.php$is_args$args;
}