Apache Find Default or Main DocumentRoot

When using the Apache HTTPD web server, a request is served by the matching <VirtualHost> block specified in the configuration. The DocumentRoot directive inside a virtual host allows us to specify how we want a request to be served or handled. Through this directive we’re able to map the request URI to a filesystem document or file that has to be served against the request.

But what happens if we don’t specify a document root inside the virtual host ? How will Apache know where to serve files from ? That’s where the default or main document root comes into the picture.

What is the default or main document root ?

As the name already suggests, it is the default DocumentRoot value for virtual hosts when they themselves don’t specify one. So if a request matches a virtual host block which lacks a DocumentRoot directive to fulfil the request, Apache will use the default or main document root to serve the request.

Where or how is the default document root specified ? There are two places:

  • Compile-time or Runtime options of httpd.
  • The main server config which is the configuration specified outside the virtual host blocks. Any virtual host configuration basically picks up default values from the main server config.

Note: The document root value specified in the main server config will override the one inherited from compile-time or runtime option.

How do I find the default document root value or path ?

We can use the apachectl or httpd command line programs to check what path on the filesystem acts as the default document root for our web server installation.

$ apachectl -D DUMP_RUN_CFG
...
Main DocumentRoot: "/var/www/html"
...

# Other variations of the command
$ apachectl -t -D DUMP_RUN_CFG
$ apachectl -S

# With httpd
$ httpd -D DUMP_RUN_CFG
$ httpd -t -D DUMP_RUN_CFG
$ httpd -S

The command above dumps a bunch of information out of which you need to look for the Main DocumentRoot line. This is the path that Apache uses as the default document root which is also generally used to serve off the welcome page on new Apache installations.

Can I change the default document root directory ?

Yes, you totally can! In order to change or override the value that we see in the command’s output above, all we have to do is set or change the DocumentRoot directive in the main server config file.

DocumentRoot /home/codingshower/html

Just make sure to check whether the directive is already in use or not. If yes, then modify the value or simply add it.

Conclusion

  1. The default or main document root acts as the default for both virtual hosts and the main server config.
  2. It may be set in the compile time or runtime options of httpd but can be overridden with the DocumentRoot directive in the main server config and obviously in the virtual hosts too in which case its not really the “default” root anymore.

Leave a Reply

Your email address will not be published.