Example of Nginx setting password protection for a directory

  • 2020-05-07 20:56:28
  • OfStack

Sometimes you don't want a directory to be accessed, so you need to protect it with a password or something like that. I'm using Nginx, and after all that time Nginx really hasn't tried to encrypt...
Refer to 1 of the information, and then found that this can :(Debian system, in the configuration of "#..." Means there are other configurations to follow.)
1. Configure the website (if yousite.com is in /home/www, then encrypt the ooxx directory)


server {
 listen 80;
 server_name yousite.com;
 root /home/www;
 index index.php index.html;
 location ^~ /ooxx/{
  auth_basic "Authorized users only";
  auth_basic_user_file /home/.htpasswd;
 }
 #......
}

2. Install the Apache 2 tool (requires the htpasswd command)


apt-get install apache2-utils

3. cd to /home (other directories will do, but be careful to follow auth_basic_user_file 1 above), generate username and password with htpasswd

htpasswd -bdc .htpasswd username password

(note: the generated.htpasswd file may need to be set to nginx run by the user)

So you direct access to the http: / / yousite com/ooxx will prompt you to enter your user and password, input just used htpasswd set the user and password can enter!

However, then you will find that direct access to the php file inside will become a download rather than a run - - super - -

Check the nginx configuration for php:


location ~ \.php$ {
 include /etc/nginx/fastcgi_params;
 fastcgi_pass 127.0.0.1:9000;
 fastcgi_index index.php;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

That's right!

Here's how I solved it: in the location ^~ /ooxx/{... } to add one more section of the php configuration, becomes


server {
 listen 80;
 server_name yousite.com;
 root /home/www;
 index index.php index.html;
 location ^~ /ooxx/{
  location ~ \.php$ {
   include /etc/nginx/fastcgi_params;
   fastcgi_pass 127.0.0.1:9000;
   fastcgi_index index.php;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  }
  auth_basic "Authorized users only";
  auth_basic_user_file /home/.htpasswd;
 }
 #......
}

Call it a day, please refer to the Nginx official documentation for details.

Note: if you remove the location ^~ /ooxx/ ^~, you will need to enter a password to access the directory, but you can directly access the file, note.


Related articles: