18

I know that similar questions have been asked, but the available answers are not very clear, so please bear with me.

After setting up a few <VirtualHost>s in apache, I'd like to configure the _default_ ServerName so that it returns the 404 message. I.e., unless some explicitly available domain is specified in the Host http header, return 404. (Ideally something more direct than pointing to a now-nonexistent directory.)

Any help would be greatly appreciated.

Phil Hollenback
  • 14,947
  • 4
  • 35
  • 52
ezequiel-garzon
  • 577
  • 2
  • 7
  • 16

2 Answers2

31

Did you try:

Redirect 404 /
ErrorDocument 404 "Page Not Found"

in the default VirtualHost?

  • Thanks, that did it! Since it's clear my low level of expertise, I might add for my fellow newbies that the default server should appear first. (This took me a while to figure out!) – ezequiel-garzon Feb 05 '11 at 13:25
  • NOTE that if the `ErrorDocument` points to a file or url inside that vhost, it will also return a 404, thus generating an internal server error. – Cyril N. May 14 '15 at 11:53
  • This answer would work for sites where all the vhosts are contained in a single file (Eugene Fidelin's answer is more complete). When using separate .conf files for each site with a2ensite, I could not figure out how to load the default (404) configuration first. – Andy Swift Sep 03 '15 at 09:08
  • `Redirect 404 /` is enough to show the default Apache "Not Found" page and it also works inside a specific virtualhost (there can be cases when you'd like to return 404 for an entire site to make it disappear from Google SERPs) – lucaferrario Aug 08 '17 at 13:01
  • For those having the same issue as Andrez Swift: vhost configuration files are including in alphanumerical order, which makes it best practice to prefix the files with their numerical priority, allowing you to easily rearrange them. Use 000-default.conf for your "catch-all" configuration and for example 010-mysite.conf for specific vhosts. And one "gotcha" for me is that even just specifying the IP in the made it match that vhost over the default (even tho ServerName did not match)... More on vhost matching: https://httpd.apache.org/docs/2.4/vhosts/details.html – Ward D.S. Sep 11 '20 at 08:08
1

Here is example of 000-default.conf that will return 404 error if server name is not configured for Apache

<VirtualHost *:80>
  ServerName default
  Redirect 404 /
</VirtualHost>
<VirtualHost _default_:80>
  Redirect 404 /
</VirtualHost>
  • I can confirm that the second part works when all the vhosts are configured in a single file (I put it first). – Andy Swift Sep 03 '15 at 09:11
  • 1
    It might better to use 503 (Service Unavailable) instead of 404, but I doubt in practice it makes much difference, monitoring tools will usually alert for any non-200 codes. – Kris Aug 09 '17 at 11:11
  • It's working perfectly for http but not for https when I do with port 443. Do you have any idea about that? – Sohail Ahmed Feb 21 '19 at 13:53