The DocumentRoot in Apache specifies the directory where the server looks for files to serve for a domain or virtual host. On systems like Ubuntu, this is usually set to the default directory /var/www/html. However, there may be instances where you need to change this directory to better suit your organization’s needs or for easier management.

Changing the DocumentRoot involves updating the virtual host configuration file. Ensuring that Apache has the necessary permissions to access the new directory is essential. Failure to set permissions correctly can result in access errors or failed server responses.

Different Linux distributions may have variations in configuration paths, but the process of changing the DocumentRoot is generally consistent. The following steps outline how to perform this change while ensuring that Apache functions correctly.

Steps to change DocumentRoot location for Apache VirtualHost:

  1. Open the virtual host configuration file in your text editor.
    $ sudo vi /etc/apache2/sites-enabled/000-default.conf
    [sudo] password for user:
  2. Locate the DocumentRoot directive and change its path to the new directory.
    <VirtualHost *:80>
            ServerAdmin webmaster@localhost
            DocumentRoot /home/user/website
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
  3. Add a Directory block for the new path, setting the required permissions.
    <VirtualHost *:80>
            ServerAdmin webmaster@localhost
            DocumentRoot /home/user/website
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
     
            <Directory /home/user/website/>
                    #Options Indexes FollowSymLinks
                    #AllowOverride None
                    Require all granted
            </Directory>
    </VirtualHost>
  4. Ensure Apache has ownership of the new directory.
    $ sudo chown --recursive www-data:www-data /home/user/website/

    Make sure Apache has read and execute permission to the DocumentRoot folder along with its parent folder.
    Related: How to change file and folder permissions in Linux

  5. Update the SELinux context if your distribution uses SELinux.
    $ sudo semanage fcontext -a -t httpd_sys_rw_content_t "/home/user/website(/.*)?"

    This applies to distributions that implements SELinux such as CentOS, RHEL and Fedora Use httpd_sys_content_t instead for readonly access for Apache on the folder.

  6. Restart or reload the Apache service to apply the changes.
    $ sudo systemctl restart apache2 # Ubuntu, Debian, openSUSE and SLES
    $ sudo systemctl restart httpd # CentOS and Red Hat
  7. Verify the configuration by accessing the site.
    $ curl 127.0.0.1
    Hi, I'm located in /home/user/website
Discuss the article:

Comment anonymously. Login not required.