Method to add virtual host functionality on the Apache server

  • 2020-05-14 05:26:24
  • OfStack

By default, Apache holds the web root directory under /var/www/html/. In other words, by default, one server can only run one website. But 1 performance is still a good server, if only run 1 site, is not a bit of waste? In fact, Apache is to support the virtual host function, to virtual host mode can run N sites.

Apache open virtual host function method is simple, 6.3 and 2.2 Apache CentOS, for example, in/etc httpd/conf d/directory to create a vhost conf configuration files, content format is as follows:


NameVirtualHost *:80

<VirtualHost *:80>
   ServerName aaa.com
   ServerAlias www.aaa.com
   DocumentRoot /srv/www/aaa.com/public_html/
</VirtualHost>

<VirtualHost *:80>
   ServerName bbb.com
   ServerAlias www.bbb.com
   DocumentRoot /srv/www/bbb.com/public_html/
</VirtualHost>

Then create directories for the two sites:


$ mkdir -p /srv/www/aaa.com/public_html
$ mkdir -p /srv/www/bbb.com/public_html

In the above two domains, add one A record to point to the IP address of the server, and then restart the Apache server:


$ service httpd restart

If you need to log access logs and error logs, and to implement URL rewrite, you need to make the following modifications:


<VirtualHost *:80>
   ServerAdmin webmaster@aaa.com
   ServerName aaa.com
   ServerAlias www.aaa.com
   DocumentRoot /srv/www/aaa.com/public_html/
   ErrorLog /srv/www/aaa.com/logs/error.log
   CustomLog /srv/www/aaa.com/logs/access.log combined
   <Directory /srv/www/aaa.com/public_html/>
     Options FollowSymLinks
     AllowOverride All
     Order allow,deny
     allow from all
   </Directory>
</VirtualHost>

At this point, the virtual host creation is complete, with different domain access, the server will return different content.

It should also be noted that if the server is also accessed at this point using the IP address, the content returned will no longer be that of /var/www/html/, but that of the first virtual host in the vhost.conf configuration file.


Related articles: