Clearing cache causes nginx error
We had a similar issue and traced it to the nginx fastcgi_read_timeout option. Because the code to clear the cache doesn't send any output to the browser until it finishes, nginx doesn't receive anything from PHP for 60 seconds. At this point, the default fastcgi_read_timeout is reached, so nginx aborts the request.

When you added the echo $path, you forced PHP to output something, which meant that nginx had something to read, so it didn't reach the timeout.

You should try increasing the fastcgi_read_timeout to, say, 120s and see if that helps.