Protecting website folders using .htaccess
Learn how to use .htaccess files to prevent unauthorized access to web site folders.
The .htaccess file is a configuration file that Apache-based web servers use. In .htaccess files, you can use directives to redirect requests to different URLs, control directory listings, specify custom error documents, and more.
Note
If there are any misconfigured rules or incorrect syntax in an .htaccess file, users see an "Internal Server Error" message when they visit a page in the same directory. Be very careful when you make any changes to an .htaccess file.
Code to protect directories and subdirectories
You can protect files, directories and subdirectories to help prevent unauthorized access. The following parameters are used below to protect the folders:
-
AuthType Basic: This specifies the web server's authentication method.
-
AuthName "Dialog Prompt": This provides the title of the authentication dialog box.
-
AuthUserFile path: This instructs the web server where to look for the username/password file. Replace path with the relative path to your .htpasswd file.
-
Require valid-user: This instructs the web server which users in the .htpasswd file have access to the folder. The valid-user portion indicates that the folder is viewable to all users in the file.
Protect the main web directory
To protect the main web directory, add the following code to the .htaccess file:
#Protect Directory
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /home/username/example.com/.htpasswd
Require valid-user
Protect a web subdirectory
To protect a subdirectory add the following code to the .htaccess file. This example shows you how to protect the subdirectory named members:
#Protect Directory
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /home/username/example.com/members/.htpasswd
Require valid-user
More Information
To view a tutorial for using .htaccess files, please visit http://httpd.apache.org/docs/2.2/howto/htaccess.html.
Related Articles
Updated 3 days ago