Restrict uploaded files into a custom folder to logged in users by htaccess: looking for Nginx – not only Apache – solution

The nginx equivalent of

RewriteCond %{REQUEST_URI} ^.*wp-content/uploads/restricted/.*
RewriteRule ^wp-content/uploads/(restricted/.*)$ dl.php?file=$1 [QSA,L]

will be the

location ~ ^/wp-content/uploads/(?<file>restricted/.*) {
    rewrite ^ /dl.php?file=$file last;
}

If you want to apply this to several folders under /wp-content/uploads, use

location ~ ^/wp-content/uploads/(?<file>(?:restricted1|restricted2|restricted3)/.*) {
    rewrite ^ /dl.php?file=$file last;
}

I don’t think there can be any other solution for nginx but to alter its configuration, after all the fact it has all the rules compiled at the startup instead of checking every single folder for .htaccess on every request is one of the reasons that it so outperforms Apache.