Whitelisting IPs in Apache and RHEL

November 2012 ยท 2 minute read

I had a problem recently where I wanted to whitelist a set of IPs (and that set may change anytime) to allow them to use a reverse-proxy on Apache in an RHEL (Red Hat Enterprise Linux) environment. Here’s some instructions on how to do this yourself.

  1. So the first step is to edit your Apache config. I was doing this in an SSL context so I edited the /etc/httpd/conf.d/ssl/conf file and put this in the VirtualHost part: ``` RewriteEngine On

RewriteMap ipslist txt:/var/www/whitelist.txt RewriteCond %{REMOTE_ADDR} ^(.*)$ RewriteCond ${ipslist:%1|black} ^black$ [NC] RewriteRule ^ - [F] ```

The first line turns on Apache’s Rewrite module, this is required for this setup to work. Then it creates a RewriteMap called ‘ipslist’ located at /var/www/whitelist.txt. I advise putting this in /var/www because if done in some other /home directory, it won’t work with SELinux enabled as it won’t allow Apache to access files there. Chmod’ing the whitelist.txt to 664 is a decent permission.

  1. Create your whitelist. This is the “/var/www/whitelist.txt” file. For this, just put in the IP you want whitelisted followed by a space then “white”. Then the next IP on the next line. So a sample one could be: white white and so on.

  2. Restart Apache, just do “sudo /etc/init.d/httpd restart”

  3. That should be it! All the rest of your config can be as it is, including proxying functionality or whatever because the URL rewriting happens before all that.

The nice thing about the “RewriteMap” function is that you can change the whitelist.txt anytime you want and you don’t have to restart or reload Apache! It’ll automatically pick up on the change from the file’s changed date and update it.