Disable Direct IP Access to Apache Website

Apache helicopter.

I want to share how I solved an issue with Cache Enabler caching duplicate copies of my WordPress website content. I should note that my website is hosted on a shared host that is running Apache. If you are using Cache Enabler, you will see your pages and posts cached under, for example:

1
2# domain.com/wp-content/cache/cache-enabler
3
4$ ls
5domain.com/

All the cached pages and posts are under the website domain-name directory. My problem was, I was also seeing two additional directories that looked like:

1
212.34.56.78/ 12.34.56.78:443/ domain.com/

The IP address was the address being used by my website domain. Under these "IP" directories, I was seeing duplicate copies of my posts and pages being cached. And, when I tried to clear my cache, the files under the IP directories were not being cleared. Also, I do not want folks accessing my website directly via my domain IP, possibly bypassing my WordPress security measures.

My solution was to add a bit of code to my .htaccess file. I had to use the .htaccess method because my site is on a shared Apache host. This is the code that I added:

 1
 2# public_html/domain.com/.htaccess
 3
 4# BEGIN My additions
 5<IfModule mod_rewrite.c>
 6RewriteEngine On
 7
 8# If the user/agent is trying to access the domain.com domain IP directly ...
 9RewriteCond %{HTTP_HOST} ^12\.34\.56\.79
10
11# Then deny all access
12RewriteRule ^.*$ - [F,L]
13</IfModule>
14# END My additions

A few notes. Of course, use your actual website domain IP address. I placed this chunk of code at the beginning of my .htaccess file in my WordPress site root directory. If you had the same issue as I did with Cache Enabler creating the "IP" directories, you will have to manually remove them. They should not reappear.

The RewriteRule generates a "403 Forbidden" response for any direct IP access attempted.

The 403 Forbidden Response to a Direct IP access attempt.

If HTTPS is enabled, they may first be presented with an unsecured certificate window, but it's still possible to click through the options to access the website through the direct IP. If so, the 403 Forbidden response will still be displayed.

Final Thoughts

I like using the Cache Enabler plugin because it is lightweight and creates static HTML files.