Security Configurations for NGINX

In this tutorial we will show how to set up the additional security configurations for your PHP application hosted with NGINX application server.

You can use the following types of security configurations:


  • Security through authentication
  • To provide this, come through the next steps:

    1. Generate hash from your password. For that you can use any htpasswd tool or online service (for example, http://www.htpasswdgenerator.net/).
    2. Create simple text file with previously generated hash.
    3. Click Config button for your server.
    4. Upload the created file to the /var/www/webroot/ROOT directory.

    5. password hash nginx
    6. In the /etc/nginx directory, open nginx.conf file and modify directory configurations:

      • authentication for the whole application

      Modify the location configurations by adding the following strings:

    7. auth_basic "Restricted area";
      auth_basic_user_file /var/www/webroot/ROOT/.htpasswd;



      • authentication for the separate directory

      Add the following location strings stating the path to the required directory:

      location ~ /directory_path {   
      auth_basic  "Restricted";   
      auth_basic_user_file /var/www/webroot/ROOT/.htpasswd;
      }

      nginx directory authentication

      1. Save the changes and restart NGINX

        As a result, while accessing the application or the protected directory a user will be requested to authenticate.


        authentication required



      1. Security through setting up criteria

You can provide security for your application through setting up different criteria, for example, allow or deny access by IP address.

  1. The Allow and Deny directives are used to specify which clients are or are not allowed access to the server. The rules are checked in sequence until the first match is found.

  2. Open nginx.conf file in the /etc/nginx directory and add necessary directives:
  • deny access to the whole application

    Modify the location configurations using the strings of the following type:

    deny  xx.xx.xx.x;
    allow xx.xx.xx.x;
    deny all;

    deny access nginx
    • deny access to the separate directory

    Add the following location strings stating the path to the needed directory:

    location /directory_path {   
    deny    xx.xx.xx.x;   
    allow   xx.xx.xx.x;   
    deny    all;
    }

    deny ip access

    As a result, a user with any IP except of the allowed ones will see the 403 error while trying to open your application.

    403 forbidden nginx
    Note:
  • Denying access through IP makes sense only if you use Public IP feature.
  • Both criteria access restrictions and password-based authentication may be implemented simultaneously. In that case, the Satisfy directive is used to determine how the two sets of restrictions interact. More information you can get here.