Tip: CentOS 7 is old. Newer systems such as AlmaLinux and Rocky Linux work in a very similar way.
What is a virtual host?
Apache is a web server program. A virtual host is a set of rules for one website. It lets one server show different sites, like one post office with many mailboxes. Visitors who ask for example.com get one site. Those who ask for another.com get another.
Steps
- Log in to your server over SSH as root.
- Install Apache if you do not have it:
The last two lines make Apache start on boot and start it now.yum install httpd -y systemctl enable httpd systemctl start httpd - Create a folder for the site's files:
mkdir -p /var/www/example.com/public_html - Create a simple test page:
echo "Hello from example.com" > /var/www/example.com/public_html/index.html - Set the owner so Apache can read the files:
chown -R apache:apache /var/www/example.com chmod -R 755 /var/www - Create folders for the settings files, if they do not exist:
mkdir -p /etc/httpd/sites-available /etc/httpd/sites-enabled - Tell Apache to read that folder. Open
/etc/httpd/conf/httpd.confwithnanoand add this line at the end:IncludeOptional sites-enabled/*.conf - Make the site file
/etc/httpd/sites-available/example.com.confwith this content:<VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public_html ErrorLog /var/log/httpd/example.com-error.log CustomLog /var/log/httpd/example.com-access.log combined </VirtualHost> - Enable the site by linking it:
ln -s /etc/httpd/sites-available/example.com.conf /etc/httpd/sites-enabled/ - Check the settings for mistakes:
You want to see "Syntax OK".apachectl configtest - Restart Apache:
systemctl restart httpd - Open ports 80 and 443 in the firewall if it is on:
firewall-cmd --permanent --add-service=http firewall-cmd --permanent --add-service=https firewall-cmd --reload - Point your domain's A record to the server IP, then open the domain in a browser. You should see your test page.
Repeat steps 3 to 11 for each extra website. Use a new domain name each time.
Warning: a typing mistake in the settings can stop Apache. Take a copy of httpd.conf before you change it.
Tip: If you see the default Apache page, check that
ServerName matches the address you typed.Quick recap
- A virtual host lets one server show many sites.
- Make a folder, a test page and a
.conffile for each site. - Run
apachectl configtestbefore restarting. - Open ports 80 and 443 and point your domain to the server.