Apache – Return 404 for all execept selected

apache-2.2mod-rewrite

I am seeking for method to prevent access to WordPress admin folder "wp-admin", but also i need apache to generate 404 error (Not found) for all, but not selected IPs.
I found this post Returning 404 code for unauthorized attempts and tried Rewrite solution, but does not work for me.

So i keeping all websites in /usr/local/www/apache22/data
and tried to use such config in httpd.conf (Apache2.2 FreeBSD 9.1)

<Directory "/usr/local/www/apache22/data">
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !=77.120.9.3 [OR]
RewriteCond %{REMOTE_ADDR} !=77.120.9.5
RewriteRule ^wp-admin($|/) - [L,R=404]
</Directory>

For example, location of wp-admin for website is: /usr/local/www/apache22/data/doman.com/wp-admin

Best Answer

OK, First let me say that your entire premise is flawed: There are many other ways besides the presence of /wp-admin to determine that you're using Wordpress. You're attempting Security through Obscurity, and since you're not obscuring everything you aren't doing a particularly elegant job of it.


Those inherent problems aside, at a quick glance your RewriteRule seems to be wrong.
Per the Apache documentation:

What is matched?

In VirtualHost context, The Pattern will initially be matched against the part of the URL after the hostname and port, and before the query string (e.g. "/app1/index.html").

In Directory and htaccess context, the Pattern will initially be matched against the filesystem path, after removing the prefix that led the server to the current RewriteRule (e.g. "app1/index.html" or "index.html" depending on where the directives are defined).

Simply put that means you need more of the path to wp-admin in your rule if you want to do this in the Directory context (like ^domain.com/wp-admin($|/)). The simple/naive fix would be to change your regex to ^.*wp-admin($|/) and just match anything that contains wp-admin (which is also a good way to verify that the rule itself is being parsed).

If you insist on pursuing this avenue of "security" though I would advise making this change in the VirtualHost context (or /wp-admin/.htaccess file) instead of in the Directory context for your whole server. It is both simpler to write and more robust. (Your current solution breaks if someone on your server DOESN'T want their wordpress admin page locked down (and there are probably a lot of people who won't -- anyone with a dynamic IP for example). Doing this in each VirtualHost or a .htaccess file allows you to keep certain sites "unlocked".)

Related Topic