vodoraslo.xyz/content/articles/blog/restrict-unwanted-access-with-http-basic-auth-nginx-and-apache.md

65 lines
1.8 KiB
Markdown
Raw Permalink Normal View History

---
title: "Restrict Unwanted Access With HTTP Basic Authentication - NGINX and Apache"
date: 2024-09-05T17:05:07+03:00
draft: false
---
Here's how to only allow authenticated users to view your websites - great way to boot freeloaders and guarantee your system's (*or your vps'*) resources for yourself.
The guide is meant for debian but can be easily adapted to suit your needs. I assume you have followed Luke Smith's tutorial and have NGINX running with certbot for certificates.
## Create a username and password for authentication (*or more than 1 user*)
First:
```bash
sudo apt install apache2
```
Apache2 is only needed to create its files in /etc/ otherwsie apache2-utils commands below will fail. My configuration uses NGINX so I'll delete apache2.
Second:
```bash
sudo apt install apache2-utils
```
Third:
```bash
sudo apt remove apache2
```
Create a username you wish to authenticate with the following comnmand:
```bash
sudo htpasswd -c /etc/apache2/.htpasswd admin1
```
You will be prompted to provide a password, feel free to generate a secure 32+ character one and save it in your password manager of choice.
If you wish to create multiple other users simply remove `-c` from the command and change the name.
```bash
sudo htpasswd /etc/apache2/.htpasswd admin2
```
Then provide a new password (the same password can also work but it's more secure that way).
## Add the `htpasswd` file to NGINX
Navigate to the NGINX configuration file you wish to protect:
```bash
nano /etc/nginx/sites-available/<yourFileHere>
```
Add the following in the same `server` block and on the same level as `listen [::]:443 ssl;`:
```nginx
auth_basic "Administrators Area";
auth_basic_user_file /etc/apache2/.htpasswd;
```
2024-09-13 16:00:58 +02:00
Further reading [here](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/).