Шаблон nginx конфига
Reverse Proxy + Basic Auth
Проксирование с HTTP Basic Authentication — защита dev-стендов и внутренних сервисов
Пример конфига
nginx.conf
upstream auth_backend {
server 127.0.0.1:8000;
keepalive 16;
}
server {
listen 80;
listen [::]:80;
server_name example.com;
server_tokens off;
client_max_body_size 10m;
access_log /var/log/nginx/basic-auth-access.log combined;
error_log /var/log/nginx/basic-auth-error.log warn;
location / {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://auth_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_read_timeout 60s;
proxy_connect_timeout 10s;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
Как настроить
-
Установите apache2-utils для создания паролей: apt install apache2-utils
-
Создайте файл паролей: htpasswd -c /etc/nginx/.htpasswd username (флаг -c создаёт новый файл)
-
Добавьте ещё пользователей (без -c): htpasswd /etc/nginx/.htpasswd anotheruser
-
Убедитесь что файл .htpasswd читаем nginx: chown www-data:www-data /etc/nginx/.htpasswd && chmod 640 /etc/nginx/.htpasswd
-
Скопируйте конфиг в /etc/nginx/sites-available/, активируйте и перезагрузите: nginx -t && systemctl reload nginx