Htaccess order Deny,Allow rule

.htaccessapache-2.2

I'd like to dynamically add IPs to a block list via htaccess. I was hoping someone could tell me if the following will work in my case (I'm unsure how to test via localhost).

My .htaccess file will have the following by default:

order allow,deny
allow from all

IPs will be dynamically appended:

Order Deny,Allow
Allow from all
Deny from 192.168.30.1

The way I understand this is that it is by default allow all with the optional list of deny rules. If I'm not mistaken Order Deny,Allow will look at the Deny list first, is this correct?

And does the Allow from all rule need to be at the end?

EDIT 1

If I'm not mistaken I need to do this based on jeffatrackaid's answer:

Order Allow,Deny
Allow from all
Deny from 192.168.30.1

EDIT 2

For the sake of completeness, this is probably more appropriate for my requirements:

Order Deny,Allow
Deny from 192.168.30.1

Best Answer

This rule allows everyone into your site.

Order Deny,Allow
Allow from all
Deny from 192.168.30.1

The Order directive determines the order in which your rules are processed. With Order deny,allow the deny list will be processed first then the allow list.

With Apache, all rules are processed with the last one matching being the effective rule.

So in this case, your last rule would be allow from all.

This means that 192.168.30.1 would initially be denied but then allowed since the allow rules are processed last.

This would produce the same result

Order Deny,Allow
Allow from all
Deny from 192.168.30.1
Allow from 192.168.30.1

Think of it this way.

  • The allow/deny rules are simply separate lists of IPs to be allowed/denied.
  • The order directive determines the order in which these lists are processed.
  • Apache evaluates all rules and acts on the result of the last matching rule.

The major confusion is that this is very different from how firewalls work where rule order and first match is often what determines access.

See: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order

Related Topic