Files
my-docs/Web-Servers/Nginx/8-auth.md

76 lines
2.0 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 🔐🔑 Nginx SSL with HTTP Basic Authentication
## 📄 Example Secure Server Block (HTTPS + Password Protection)
```nginx
listen 443 ssl;
server_name example.com www.example.com;
# 🔒 SSL Certificates (Generated by Certbot)
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 📂 Website Root
root /var/www/example.com/html;
index index.html;
# 🔑 Password-Protected Location
location / {
auth_basic "Admin";
auth_basic_user_file /etc/nginx/.htpasswd;
try_files $uri $uri/ =404;
}
```
---
## 🗂️ Explanation of Key Parts
| Directive | Purpose |
| ---------------------- | ------------------------------------------------------------------- |
| `auth_basic "Admin";` | Enables **HTTP Basic Authentication** with prompt title “Admin”. |
| `auth_basic_user_file` | Points to the `.htpasswd` file containing username/password hashes. |
| `.htpasswd` file | Stores encrypted credentials — created using `htpasswd` command. |
| SSL lines | Load the certificate and private key from **Certbot**. |
---
## 🛠️ How to Set Up Password Protection
### 1⃣ Install `apache2-utils` (for `htpasswd` tool)
```bash
apt install apache2-utils
```
### 2⃣ Create the `.htpasswd` File
```bash
htpasswd -c /etc/nginx/.htpasswd <username>
```
* `-c` creates a **new file** (omit `-c` if adding more users).
* Youll be prompted to set a password.
### 3⃣ Adjust File Permissions
```bash
chmod 640 /etc/nginx/.htpasswd
chown root:www-data /etc/nginx/.htpasswd
```
### 4⃣ Test and Reload Nginx
```bash
nginx -t
systemctl reload nginx
```
---
## ⚠️ Security Notes
* Always store `.htpasswd` **outside** your web root.
* Passwords in `.htpasswd` are hashed, but still protect the file with correct permissions.
* Works best for **admin panels**, **staging sites**, or private areas.