HOW TO: Restrict a path for logged-out users with nginx

May 7, 2019

403 Method:

To restrict a path from public access (returning a 403 page), just add this to your nginx configuration (or ask your hosting provider):

set $node 0;
set $flame 0;

if ( $request_uri ~* "wp-content/uploads" ) {
set $node 1;
} 

if ($http_cookie ~ "wordpress_logged_in") {
set $flame 1;
}

set $403page "$node:$flame";

if ($403page = "1:0") {
return 403;
break;
}

Redirect method:

To restrict a path from public access (redirecting to another page, like a login form), just add this to your nginx configuration (or ask your hosting provider):

set $node 0;
set $flame 0;

if ( $request_uri ~* "wp-content/uploads" ) {
set $node 1;
} 

if ($http_cookie ~ "wordpress_logged_in") {
set $flame 1;
}

set $403page "$node:$flame";

if ($403page = "1:0") {
rewrite ^/(.*) https://403.ie/login;
break;
}

NOTE: Don't forget to change wp-content/uploads to the path you want to restrict, and the redirect path from https://403.ie/login to your login page.