Create Virtual Hosts for Apache on CentOS

For each website (domain or subdomain) you need a Virtual Host, a file that contains information for Apache to find where the website's files are on your server, how to access them, where to write the logs, etc.

For each website (domain or subdomain) you need a Virtual Host, a file that contains information for Apache to find where the website’s files are on your server, how to access them, where to write the logs, etc.

While Ubuntu/Debian has a system to enable/disable Virtual Hosts, on CentOS you will need to do this manually if you want to keep things neat. You can always create the Virtual Hosts files in /etc/https/conf.d and skip the next steps. I prefer to mimic the Ubuntu/Debian solution.

First, create the directories where you will store the Virtual Hosts

sudo mkdir /etc/httpd/sites-available
sudo mkdir /etc/httpd/sites-enabled

Instruct Apache to load the configuration files from sites-enabled by editing the httpd.conf file

sudo vi /etc/httpd/conf/httpd.conf

Add this line at the end of the file

IncludeOptional sites-enabled/*.conf

Let’s create a new configuration file for a test domain, my-test-domain.com

sudo vi /etc/httpd/sites-available/my-test-domain.com.conf

Here is the contents of the file (I will store the Website files in /usr/share/httpd/my-test-domain; change that to your directory) :

<VirtualHost *:80>
    ServerName my-test-domain.com
    ServerAlias www.my-test-domain.com
    ServerAdmin admin@my-test-domain.com
    DocumentRoot /usr/share/httpd/my-test-domain
    
    <Directory "/usr/share/httpd/my-test-domain">
        DirectoryIndex index.php index.html
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>    
    
    ErrorLog /var/log/httpd/error.log
    CustomLog /var/log/httpd/access.log combined
</VirtualHost>

Enable the Virtual Host by creating a symlink from sites-available to sites-enabled

sudo ln -s /etc/httpd/sites-available/my-test-domain.com.conf /etc/httpd/sites-enabled/my-test-domain.com.conf

Restart Apache to load the new configuration

sudo systemctl restart httpd

Leave a Reply

Your email address will not be published. Required fields are marked *