Hosts file entry directed to a directory on localhost

blockingdirectoryhosts-filelocalhost

I have a directory setup with a nice error message at http://localhost/blocked/. I'd like to direct entries in my hosts relating to sites I've blocked to that instead of just 127.0.0.1. 127.0.0.1/blocked/ doesn't work. I'm clueless about the host file and this may not even be the best way to accomplish my goal.

To restate: I'd like to direct all requests on certain domains, example.com for instance, to http://localhost/blocked/.

Best Answer

Well, here's something you could consider:

  • Make entries in your hosts file for all the blocked domains, pointing to 127.0.0.1 (I suppose you're already doing this)
  • Make a <VirtualHost> block in your Apache configuration that has a ServerAlias line for each of the blocked domains. Or one of them could be a ServerName and the rest ServerAliases. In this virtual host, you can either redirect all requests to the existing URL of your "blocked" error page, or (perhaps simpler) just put the error page in the document root.

Here's how I'd do it:

<VirtualHost *:80>
    ServerName blocked.localhost
    ServerAlias example.com
    DocumentRoot /var/www/blocked.localhost/htdocs
    # put the usual <Directory> section for that document root
</VirtualHost>

and move the whole contents of the blocked/ directory (on your filesystem) to /var/www/blocked.localhost/htdocs. Obviously the pathnames are just examples.

Make sure a NameVirtualHost *:80 line appears somewhere in your Apache configuration. (Or if you want to catch requests on ports other than 80, that can be arranged as well)