Virtual Host

Posted on

Setup Directories

Host more than one domain by adding a directory for each website under /var/www/

sudo mkdir -p /var/www/website-1.com/html
sudo mkdir -p /var/www/website-1.com/log

assign ownership to environment $USER value

sudo chown -R $USER:$USER /var/www/website-1.com/html
sudo chmod -R 755 /var/www

Create demo website

sudo nano /var/www/website-1.com/html/index.html
<html> 
  <head> 
    <title>Welcome to website-1.com!</title> 
  </head> 
<body> 
 <h1>Success! The website-1.com virtual host is working!</h1> </body> 
</html>

Create sites-available and enabled directory

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

Add directory to Apache configuration

sudo nano /etc/httpd/conf/httpd.conf

add to the end of file “IncludeOptional sites-enabled/*.conf”
save and close the file

Create a config file

sudo nano /etc/httpd/sites-available/website-1.com.conf
<VirtualHost *:80>
    ServerName www.website-1.com 
    ServerAlias website-1.com 
    DocumentRoot /var/www/website-1.com/html 
    ErrorLog /var/www/website-1.com/log/error.log 
    CustomLog /var/www/website-1.com/log/requests.log combined
</VirtualHost>

Save and close file

Enable conf files in apache

sudo ln -s /etc/httpd/sites-available/website-1.com.conf /etc/httpd/sites-enabled/website-1.com.conf

Adjust SELinux Permissions

Directory Policy for Apache

to get current context type

sudo ls -dZ /var/www/website-1.com/log/

The current context httpd_sys_content_t only allows for read only.
Changing the context to httpd_log_t will grant apache to modify log files

sudo semanage fcontext -a -t httpd_log_t "/var/www/website-1.com/log(/.*)?"

Make the changes persistent

sudo restorecon -R -v /var/www/website-1.com/log

list the context to see changes

sudo ls -dZ /var/www/website-1.com/log/

Restart the Apache server

sudo systemctl restart httpd

Test Virtual Host

Check if log files were created

ls -lZ /var/www/website-1.com/log

Check on web browser http://IPaddress the website create above should render.

https://www.digitalocean.com/community/tutorials/how-to-install-the-apache-web-server-on-centos-7