NGINX: haccess и htpasswd

Автор: | 06/10/2014

nginx_logoСоздаём файл пароля, как и в случае с Apache HTTP:

# htpasswd -c /var/www/vhosts/.htpasswd username
New password:
Re-type new password:
Adding password for user username

Редактируем файл настроек виртуалхоста, например /etc/nginx/conf.d/newsite.com.conf, и добавляем строки:

auth_basic – указатель того, что имеет место авторизация + заголовок страницы;
auth_basic_user_file – указывает на файл с логинами-паролями;

В результате – получаем примерно такую конфигурацию:

server {
    server_name newsite.com;
    ....
    root /var/www/vhosts/newsite.com;

    location / {
        index index.html index.htm index.php;
        auth_basic_user_file /var/www/vhosts/.htpasswd;
        auth_basic "Password-protected Area";
    }

    location ~ .php$ {
        include /etc/nginx/fastcgi_params;
        ...
    }
}

Или, что бы закрыть только один определённый файл – создаём ещё один блок location, например – ограничим доступ к файлу info.php в коне сайта:

server {
    server_name newsite.com;
    ...
    root /var/www/vhosts/newsite.com;

    location ~info.php {
        auth_basic_user_file /var/www/vhosts/rtfm/.htpasswd;
        auth_basic "Password-protected Area";
    }

    location / {
        index index.html index.htm index.php;
    }

    location ~ .php$ {
        include /etc/nginx/fastcgi_params;
        ...
    }
}

Проверяем конфигурацию:

# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Перезапускаем NGINX:

# service nginx restart
Stopping nginx:                                            [  OK  ]
Starting nginx:                                            [  OK  ]

Пробуем зайти:

# curl http://newsite.com | head -n 5
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<style type="text/css">
body {background-color: #ffffff; color: #000000;}
body, td, th, h1, h2 {font-family: sans-serif;}
100 16312    0 16312    0     0   708k      0 --:--:-- --:--:-- --:--:-- 1137k
curl: (23) Failed writing body (72 != 8192)

И ещё раз – на защищаемый ресурс:

# curl http://newsite.com/info.php
<html>
<head><title>401 Authorization Required</title></head>
<body bgcolor="white">
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.6.2</center>
</body>
</html>

Можно просто воспользоваться конвертером, например – тут>>>.

Например, что бы закрыть каталог wp-admin – в блоке server указываем:

 location /wp-admin/ {

     index index.php;

     auth_basic_user_file /var/www/vhosts/rtfm/.htpasswd;
     auth_basic "Password-protected Area";
       location ~ .php$ {
         include /etc/nginx/fastcgi_params;
         fastcgi_pass  127.0.0.1:9003;
         fastcgi_index index.php;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      }
 }

Или – закрыть всё, но оставить открытой только директорию public:

server {
    ...
    auth_basic "closed website";
    auth_basic_user_file conf/htpasswd;

    location /public/ {
        auth_basic off;
    }
}