There are plenty of guides that describe this already, but I find it frustrating to find a clear, concise write-up of what’s needed to get some simple username/password HTTP authentication to work just with .htaccess code.
So, here’s the short version.
Create an htpasswd file
This is a simple file that holds the username and (encrypted) password of the users you want to allow access.
$ htpasswd -c /var/www/vhosts/site.tld/passwd/htaccess.passwd mattias
The above will create a new file at that location and configure a user called “mattias”, you’ll be prompted (twice) for your password.
The -c
parameter makes a new file, if you want to add new users to an existing passwd file, use this;
$ htpasswd /var/www/vhosts/site.tld/passwd/htaccess.passwd jasper
In the end, the file looks like this:
$ cat /var/www/vhosts/site.tld/passwd/htaccess.passwd mattias:$apr1$656eUsUz$305AHL.2PAC.U2UTBdlql0
That’s an encrypted password, to reset it, run the above command again for the same username, it’ll overwrite the password.
If you want to use the password file above (because it’s quick and easy copy/pasting): that encrypted password in plain text is “nucleus", so you can log in with the user “mattias” and password “nucleus”.
HTTP authentication in .htaccess
Now, once you have the file, add the following in your .htaccess. This snippet of code will work for an Apache 2.2 and Apache 2.4 configuration. Just make sure you change the path to point to your htpasswd file.
$ cat .htaccess <IfModule mod_authn_file.c> # For Apache 2.4 or later AuthType Basic AuthName "Please provide username and password" AuthBasicProvider file AuthUserFile "/var/www/vhosts/site.tld/passwd/htaccess.passwd" Require valid-user </IfModule> <IfModule mod_auth.c> # For Apache 2.2 or lower AuthType Basic AuthName "Please provide username and password" AuthUserFile "/var/www/vhosts/site.tld/passwd/htaccess.passwd" Require valid-user </IfModule>
Next time you visit your site, you’ll be prompted for an HTTP username and password.