The DocumentRoot is a directive in the Apache web server that specifies where the web files for a particular domain or virtual host reside. By default, many distributions like Ubuntu place these files in the /var/www/html directory. However, for reasons like organizational structure, easier backup, or file system preferences, one might need to move the DocumentRoot to another location, say /home/user/website.

Adjusting the DocumentRoot is commonly done when setting up new websites or when migrating web content. However, care should be taken to ensure that the Apache server has the necessary permissions to access the new directory.

Changing the DocumentRoot for a specific virtual host in Apache requires editing the virtual host's configuration file. Different Linux distributions might have slightly different paths and structures for Apache configurations, but the concept remains the same.

Steps to change DocumentRoot location for Apache VirtualHost:

  1. Edit Apache configuration file using your preferred text editor.

    $ sudo vi /etc/apache2/sites-enabled/000-default.conf
    [sudo] password for user:
  2. Set the path in DocumentRoot directive within VirtualHost configuration to new location.

    <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 Directory directive to provide necessary permissions for the folder.

    <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. Change folder ownership of folder to ensure it's accessible by Apache.

    $ 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. Change SELinux context if required.

    $ 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 Apache service for the changes to take effect.

    $ sudo systemctl restart apache2 # Ubuntu, Debian, openSUSE and SLES
    $ sudo systemctl restart httpd # CentOS and Red Hat
  7. Access the website to test if the changes was successful.

    $ curl 127.0.0.1
    Hi, I'm located in /home/user/website