May 30th, 2020

Adding Basic Auth to site on Laravel Forge

Here I am going to outline how I added basic auth to my build environment for this site. I switched servers to run on Laravel Forge, and the only instructions I could find for how to do this were several years (and versions of Forge) old. I know the server is running nginx, and I know how to do this manually, but I don’t want to go around any infrastructure Forge has setup and ham-fist it.

Generate htpasswd

First thing you need to do is generate your htpasswd file. Search for an htpasswd generator and enter in a username and password. The result will be a single line string separated by a colon. Copy that entire string and keep it handy.

Create htpasswd file

Next, SSH into your server, and create the file .htpasswd
I created mine in /etc/nginx/

cd /etc/nginx
sudo nano .htpasswd

(if doing multiple sites, you can name this whatever you want, just remember to reference it when adding it to the config below)

paste in your generated authorization line here

ctrl+x and then y to save the file.

Edit nginx config

Next go to your Forge dashboard, and go to your specific site. At the bottom of the screen there is a grey button/pill/badge labled files.
Click that, and then edit nginx configuration.

After that, you need to add two lines to your configuration file. Be careful not to disturb anything you are unsure of. Find the top of your server{} block and you need to add two lines. The first, the directive to restrict content and display the message of the alert box. The second line, is the path to your .htpasswd file.

auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;

If you want to do this with multiple sites, you should name your files something more recognizable, such as sitename.htpasswd and then reference those specifically in your settings.