DEV Community

Cover image for Protect Directories Using APACHE
Walter Nascimento
Walter Nascimento

Posted on

Protect Directories Using APACHE

Apache has a setting that causes anyone accessing the site to be prompted for a password.

While not the best way to keep your files safe, in a very quick and simple way to do

so let's go

Htaccess

To request a password on your apache server, you must tell to apache that it needs to request a password, as one of the ways is basic authentication.

touch .htaccess
Enter fullscreen mode Exit fullscreen mode

After creating the file edit it with the following settings:

.htaccess
AuthType Basic
AuthName "Restricted Files"
AuthUserFile "/usr/local/security/.htpasswd"
Require valid-user
Enter fullscreen mode Exit fullscreen mode

Where it says "Restricted Files", you can substitute whatever you want to appear to the user.

and where is the location of the .htpasswd file, you must first create the file, being possible to use the htpasswd file that comes in the linux environment

htpasswd -b -c .htpasswd <user> <password>
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก NOTE: Replace <user> with the desired username and <password> with the desired password

if you don't want to use the command above you can also create a file manually and access any generator on the internet, for example:

https://hostingcanada.org/htpasswd-generator/

Conf

If you are creating the server for the first time and want to make less edits, you can leave the settings inside the conf file:

 <Directory /var/www/html>
   AuthType Basic
   AuthName "Authentication Required"
   AuthUserFile "/etc/htpasswd/.htpasswd"
   Require valid-user
 </Directory>
Enter fullscreen mode Exit fullscreen mode

Code and Example

If you prefer, I have a ready-to-use repository:
https://github.com/walternascimentobarroso/PHP-Apache

Extras

If you want to delve deeper into apache, visit this link and the documentation itself ;)

References

https://httpd.apache.org/docs/2.4/howto/auth.html
https://httpd.apache.org/docs/2.4/programs/htpasswd.html
https://hostingcanada.org/htpasswd/


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
๐Ÿ˜Š๐Ÿ˜Š See you! ๐Ÿ˜Š๐Ÿ˜Š


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)