Apache Directory Authentication With htaccess

Apache directory authentication with htaccess tutorial will be useful for you if you have some public directory on your apache server that you need to restrict access for other people.
I will assume that you have apache installed on your system.

If you don’t have Apache installed, see our LAMP Installation tutorial.

Apache directory authentication with htaccess

Lets now proceed to configuring authentication.

1. Update your system

First check if there are any updates:

2. Install htpasswd for making password

Next we will use an apache tool for making passwords called htpasswd, to install that, run:

If you are running htpasswd for the first time, you will run this command:

Note: <username> is username that you want to enter when you visit protected directory (example: john)

Next time you’ll run command from above without -c, like this:

/etc/apache2/.htpasswd will contain all usernames with encrypted passwords.

3. Create .htaccess file

Now we’ll proceed with setting up .htaccess file.

This can be done with apache Virtual Host Definition but this will be done in another tutorial.

Go to directory you want to protect:

Note: Replace protected with the name of your directory

Create .htaccess file with nano or any other text editor:

We’ll use Basic authentication and we’ll allow access for every user with valid credentials.

Copy the following code to htaccess file

Ctrl+X to close file, enter Y to save changes and that’s it.

Now point your browser to the directory URL

Pop up should appear and ask for login credentials.

If you enter invalid credentials or you click Cancel, you’ll see an “Unauthorized” page error

If it’s not working, restart Apache server:

And try again, it should be working now.

You can visit official Apache documentation for additional information.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *