Access Control for Apache 2.4 (and 2.2)

Category: Blog • Posted by Jeff Starr • Updated:

Throughout the book, I explain various techniques for controlling access to web pages. For example, if you are getting hit with an attack from a specific range of IP addresses, you can add directives to block them based on the host address or other variables. It is a common technique that I've discussed numerous times. With Apache 2.4, there are changes to the directives that are used for access control. This tutorial explains the changes and then shares some examples to help you implement the best solution for your site.

Note: this topic is covered in the book on page 147, "Allow/Deny directives for Apache 2.4+" (in Chapter 7: Tighten Security).

Changes in Apache 2.4

Summary:

Apache 2.2 uses the authz_host_module to control access using directives like Deny, Allow, and Order.

Apache 2.4 uses also the authz_host_module for access control, but also uses the authz_core_module, which provides the new Require directive.

So basically, the rules to control access are different depending on your version of Apache. To help with this, I've provided numerous examples below.

Code Examples

Here are some examples that compare the different syntax required depending on your version of Apache.

Important! Do not use 2.2 and 2.4 directives on the same server; it may cause issues and/or errors.

Deny all requests

# DENY ALL REQUESTS

# Apache 2.2
Order deny,allow
Deny from all

# Apache 2.4
Require all denied

Allow all requests

# ALLOW ALL REQUESTS

# Apache 2.2
Order allow,deny
Allow from all

# Apache 2.4
Require all granted

Allow only example.com

# ALLOW ONLY EXAMPLE.COM

# Apache 2.2
Order Deny,Allow
Deny from all
Allow from example.com

# Apache 2.4
Require host example.com

Example: Conditional Directives

In some cases, you may not know which version of Apache you are using. In such case, the following conditional directives should give you a better idea. You can use the following code on any Apache server version 2.2 or 2.4.

# Apache 2.4
<IfModule authz_core_module>
	Require ip 123.123.123.123
</IfModule>

# Apache 2.2
<IfModule !authz_core_module>
	Order Deny,Allow
	Deny from all
	Allow from 123.123.123.123
</IfModule>

When included via .htaccess or Apache configuration file, this code will detect the correct version of Apache and use the proper directives for access control. So for Apache 2.4 and better, we check for the authz_core_module and then allow only IP address 123.123.123.123. Or if authz_core_module does not exist, the server is Apache 2.2 or less, and so we allow only IP address 123.123.123.123 using the Order, Deny, and Allow directives.

Of course, these are just examples to show how to implement the correct access-control directives. You will want to consult the Apache docs and modify the code to suit your specific needs.