Blocking/allowing IP-addresses in Nginx

in Nginx configuration Tags: Nginx

Hypernode makes use of Nginx (pronunciation: ‘Engine X’) over Apache. Nginx has much better performance than Apache, and allows us to serve your webshop to many more visitors than Apache would. Nginx does not use .htaccess files like Apache does. This means that configuration previously done in .htaccess files now has to be done in a different format.

Blocking and allowing IP-addresses is done using the access module.

Denying everyone across the site

To deny all access from certain addresses, create a file in the nginx-directory in your homedir named server.blacklist, with the following contents:

deny 1.2.3.4;     # To deny a single server
deny 5.6.7.0/24;  # To deny a complete network

Denying everyone across the site, except for certain addresses

To deny all access, except certain addresses, add a file named server.whitelist, with the following contents:

allow 1.2.3.4;   # Allow a single remote host
deny all;        # Deny everyone else

Denying or allowing only a specific location

To deny access to everybody except certain addresses to a specific directory, create a file called server.private-dir containing:

location /private/ {   ## Use the request url, not the directory on the filesystem.
  allow 100.23.45.14;  ## Your specific IP
  deny all;
}

Denying access to your staging environment

If you want to allow only a specific ip address to your staging area, you can add the following snippet to a staging.whitelist, replacing yourdomain.hypernode.io with your base-url and YOURIP with the desired ip address.

if ($http_host ~ "yourdomain.hypernode.io:8443")  {
  set $block_me_now A;
}

if ($remote_addr != YOURIP) {
  set $block_me_now "${block_me_now}B";
}


if ($block_me_now = AB) {
    return 403;
    break;
}

19