Examples of Apache 2.4 .htaccess Directives

The Apache web server uses .htaccess files to give it additional instructions for within a folder and its sub directories. .htaccess files can be used to do many things such as redirecting a user, IP whitelisting, disabling access to certain types of files, and much more.

As I said before, a .htaccess file applies to the directory in which it is contained, and also to that directories sub directories. If one of the sub directories has an .htaccess file inside it, the sub directory’s .htaccess file is processed first.

I’ve included a few snippets as examples. Note that these snippets are for Apache 2.4. If you search for “apache htaccess,” lots of results will appear, but most of these results are for Apache 2.2. Apache 2.2 was declared end of life on 1/1/2018, so hopefully folks have been able to upgrade.

The following snippet forces a website to use HTTPS:

The following snippet enforces IP whitelisting. IP whitelisting using .htaccess files is not full proof because IP addresses can be spoofed, but it can help. You could place a .htaccess file within the “/wp-admin/” folder with this rule if you wanted only certain IP addresses to be able to access the dashboard.

This snippet enforces IP whitelisting, but this time, it redirects to the home page if the user is not in the whitelist.

This snippet requires that the user authenticate before being able to access the folder or its contents. A file with usernames and passwords must be created OUTSIDE of the web root directory (For security purposes). The format for the usernames and passwords in this file is username:encrypted-PW – here is a guide on how to generate the encrypted password. The “AuthUserFile” needs to be updated, and the “AuthName” parameter should be updated as well.

This snippet requires additional authentication only IF the user is not IP whitelisted. The notes about changing the “AuthUserFile” and “AuthName” parameters still apply.

Posted in

Leave a Comment