1

This tutorial shows how to setup Apache Virtual Hosts in CentOS 7. This is useful if you want to host more than one website on a single CentOS web server. For instructions on how to setup Apache, PHP, and SQL database on CentOS 7, check this article

Setup folder structure for your websites

We are going to create 2 folders for each website. The first will hold HTML and other content, second - log files.

/var/www/sites/domain1/html

/var/log/httpd/domain1

/var/www/sites/domain2/html

/var/log/httpd/domain2

/var/www/sites/domain3/html

/var/log/httpd/domain3

Log files will be stored in var/log/httpd/... subfolders, which is the default place to store log files in Linux. People often store Apache log files in /var/www/ subfolders, but in CentOS with SELinux enabled this can cause access denied errors. This can be fixed with chcon command, but I prefer to store all my log files in /var/logs... 

You can also place index.html files with some sample text in each html directory which we'll use later for testing.

Create folder structure for virtual host files

Create folders:

/etc/httpd/sites-available

/etc/httpd/sites-enabled

sites-available will hold virtual host config files for websites that are configured, but not necessary enabled. These files are actually ignored when Apache starts, but this system allows to easily disable and enable websites without having to delete or create new virtual host files every time we want to take a site offline and put it back online.

sites-enabled will hold symbolic links to virtual host files inside sites-available that are enabled. They will be loaded when Apache starts.

Add sites-enabled to Apache config

Open file /etc/httpd/conf/httpd.conf and at the very end of the file add following text:

IncludeOptional sites-enabled/*.conf

This will tell Apache to look for virtual host files with extension .conf in sites-enabled directory.

Create Virtual Host files

In directory /etc/httpd/sites-available create config files for each website (domain1.conf, domain2.conf, etc.) with following content:

<VirtualHost *:80>

ServerName www.domain1.com

ServerAlias domain1.com

DocumentRoot /var/www/sites/domain1/html

ErrorLog /var/log/httpd/domain1/error.log

CustomLog /var/log/httpd/domain1/access.log combined

</VirtualHost>

Change domain1 to match your domain names and directories you created previously.

If Apache can't match the requested domain to any of the virtual hosts, the first (alphabetically) virtual host site will be loaded. If you want to have more control over this, you can create a dedicated virtual host (i.e. 00_default) that will be loaded only when no matching virtual host exist. ServerName and ServerAlias should not match any of your domains (i.e. example.com) The name starts with 00 so that it is always the first virtual hosts alphabetically. The site linked to this default virtual host could show an error message, redirect to another domain, etc.

Edit httpd.conf

Edit the main Apache configuration file /etc/httpd/conf/httpd.conf according to your requirements.

In my particular case, I made following changes:

Set webmaster email address:

ServerAdmin administrator@domain.com

Set main document root:

DocumentRoot "/var/www/sites"

Configure main document root:

<Directory "/var/www/sites">

AllowOverride All

Options FollowSymLinks

</Directory>

AllowOverride All - is required if you intend to use .htaccess files for directory level configuration. By default, this is set to None, in which case .htaccess overrides would be ignored.

Options -Indexes - prevents directory listing.

Enable Virtual Hosts

To enable websites, we need to create symbolic links in /etc/httpd/sites-enabled pointing to appropriate config files in sites-available. To do this, run:

ln -s /etc/httpd/sites-available/domain1.conf /etc/httpd/sites-enabled/domain1.conf

For changes to take effect we need to restart Apache:

systemctl restart httpd.service

To disable a particular website, simply delete relevant symbolic link (or change the extension) and restart Apache.

Before going live, you can test if everything is working locally. To do this, edit the hosts file on your client machine to point domains configured inside virtual hosts to the CentOS web server's IP address. If everything was setup properly, pointing your web browser to one of the domains should load index.html file from an appropriate /var/www/sites/... directory.

2015.01

CentOS 7

###########################################

Apache HTTP Server is an open-source Web server.Apache is probably the most popular Linux-based Web server application in use. Once you have DNS correctly setup and your server has access to the Internet, you’ll need to configure Apache to accept surfers wanting to access your Web site.This document explains how to configure Apache in a number of commonly encountered scenarios for small web sites. This documentation was written for Apache HTTP Server 2.2.3 but may be usefull with other versions.

How to install Apache Server on CentOS, RedHat, Linux

About this article:  General Information

Apache Version:     httpd-2.2.3-91.el5.centos

Config FIle:            /etc/httpd/conf/httpd.conf

Port:                      80

Access Log:            /var/log/httpd/access_log

Error Log:              /var/log/httpd/error_log

Lab Scenario

Server IP Address:   192.168.1.254

Local Domains:        abc.local    and  xyz.local

Prerequisite

DNS  should be properly configured

Install Apache HTTP Server

#yum install httpd

Note: This is typically installed with CentOS by default

#chkconfig httpd  on

Restart the Apache HTTP Server daemon

# service httpd restart

How to test Apache Server on CentOS, RedHat, Linux

Access web browser for http://192.168.1.254/  ,  this page comes ( see below ) this means apache is up and running.

 

Apache Directives

DocumentRoot

The directory that contains the HTML files. Also specify this mount point when adding the service to the cluster configuration. It is only required to change this field if the mount point for the web site’s content differs from the default setting of /var/www/html/

DocumentRoot “/var/www/html

 

DirectoryIndex

The DirectoryIndex directive sets the list of resources to look for, when the client requests an index of the directory by specifying a / at the end of the directory name. Local-url is the (%-encoded) URL of a document on the server relative to the requested directory; it is usually the name of a file in the directory. Several URLs may be given, in which case the server will return the first one that it finds. If none of the resources exist and the Indexes option is set, the server will generate its own listing of the directory.

DirectoryIndex index.html index.html.var

Directory

Following directives mean:

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

<Directory “/usr/lib/cgi-bin”>

AllowOverride None

Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch

Order allow,deny

Allow from all

</Directory>

Particularly these keywords:

Directory

AllowIverride

Options: +ExecCGI -MultiViews +SymLinksIfOwnerMatch

Order

Allow

Directory  describes properties of a content directory on server’s filesystem.

AllowOverride  describes what options can be altered by .htaccess file in the Directory or its child directory.

Options describe directory options, there can be many. +ExecCGI means that CGI script execution is allowed, -MulitViews means implicit file name conversion if file is not found is turned off and +SymLinksIfOwnerMatch means symlinks will be respected if file owner is the same.

Order allow,deny means that Allow directive will be processed first, then Deny if it is set, and Allow from all means that access is not restricted.

<Directory “/var/www/html”>

Options Indexes FollowSymLinks

AllowOverride None

Order allow,deny

Allow from 192.168.1.15

</Directory>

This means  web content placed in /var/www/html  will be accessed  by  192.168.1.15 only. Similarly we retrict any website to be opened on any location or country by deny ipaddress or ip ranges

Deny from  IpAddress  

 

Multiple websites on the same server ( Virtual Hosts )

Apache Virtual Host means, We can run multiple websites on the same server.

For example, We can run both abc.local and xyz.local on a single physical server that has one Apache webserver running on it.

There are two types of Apache virtual host configurations:

1) IP-Based Virtual Host and

2) Name-based Virtual Host.  <– Recommended 

IP-Based Virtual Host ( Required NO DNS here)   < How to configure DNS ? >

On IP based Virtual Host, Server should have multiple IP Address for Multiple site for multiple website.This means that the server should have two ethernet cards or Virtual IPs, each one of them configured to the ip-address of the corresponding website that Apache virtual host will be serving.

The server contains two NIC cards or Virtual Interface, one is configured with

192.168.1.254 ip-address for xyz.local,

192.168.1.254 ip-address for abc.local 

Both these ip-address are served by a single Apache webserver running on that server using IP-Based virtual host. this is not recommended because no one will use websites on IP Address ( except some Intranet Stuff)

Name-Based Virtual Host   ( DNS Server Required for this Option )

in name based Virtual Host, when Apache webserver receives a request, it looks for the hostname in the HTTP header, and depending on the hostname, it servers different websites. This is very easy, as you need only one ip-address on that physical server; but, you update the DNS with multiple website names pointing to the same ip-address. For all practical purpose, you’ll be using only Name-based virtual host configuration.  We can use different IP Address for  different domain, should be resolved by DNS Server  ( View Video for more Explanation )

How to configure  Virtual Hosts (Multiple Website) ?

# vi /etc/httpd/conf/httpd.conf

press Shift + G   to come to bottom of the file, go some line upward, we find the required lines as given below

uncomment

NameVirtualHost *:80

copy and paste  given lines (given on the bottom of the config file )on the bottom as per no of website need to be host.

#<VirtualHost *:80>

# ServerAdmin webmaster@dummy-host.example.com

# DocumentRoot /www/docs/dummy-host.example.com

# ServerName dummy-host.example.com

# ErrorLog logs/dummy-host.example.com-error_log

# CustomLog logs/dummy-host.example.com-access_log common

#</VirtualHost>

modify  like

<VirtualHost *:80>  ServerAdmin webmaster@xyz.local  DocumentRoot /var/www/xyz.local  ServerName xyz.local  ErrorLog logs/xyz.local-error_log  CustomLog logs/xyz.local.-access_log common </VirtualHost>

<VirtualHost *:80>  ServerAdmin webmaster@abc.local  DocumentRoot /var/www/abc.local  ServerName abc.local  ErrorLog logs/abc.local-error_log  CustomLog logs/abc.local.-access_log common </VirtualHost>

Where

NameVirtualHost *:80 – Indicates that all the name-based virtual hosts will be listening on the default port 80

<VirtualHost *:80> </VirtualHost> – Enclose all the apache configuration parameters for each and every virtual host between these VirtualHost tags. Any apache directives can be used within the virtualhost container.

In the following example, we are setting up virtual host for xyz.local and abc.local  listening on the same port 80. So, there will be two <VirtualHost *:80> </VirtualHost>, one for each website.

When you go to xyz.local, the files under /var/www/xyz.local/ will be served by Apache; and the access_log and error_log

To check syntax of config file httpd.conf

[root@mail1 ~]# httpd -t

Syntax OK

Or

[root@mail1 ~]# service httpd configtest

Syntax OK

now we have to make document root for websites

# mkdir /var/www/xyz.local

# mkdir /var/www/abc.local

# chown -R apache:apache /var/www/*

Place index.html files in DocumentRoot  folder  ( view video for more explanation)

#vi /var/www/xyz.local/index.html

<html> <body> <div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;"> Test Page for domain XYZ.LOCAL </div> </body> </html> ---------------------------------------------------------------

#vi /var/www/abc.local/index.html

<html> <body> <div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;"> Test Page for domain ABC.LOCAL </div> </body> </html>

Now for testing websites on Windows Node, change setting  DNS in Windows Client to 192.168.1.254

C:\Users\vikas>ping abc.local  Pinging abc.local [192.168.1.254] with 32 bytes of data: Reply from 192.168.1.254: bytes=32 time<1ms TTL=64 Reply from 192.168.1.254: bytes=32 time=1ms TTL=64

C:\Users\vikas>ping  xyz.local

Pinging xyz.local [192.168.1.254] with 32 bytes of data: Reply from 192.168.1.254: bytes=32 time<1ms TTL=64 Reply from 192.168.1.254: bytes=32 time=2ms TTL=64   Now Open any browser and check 

#######################################################################################################

How to Serve Multiple Domains Using Virtual Hosts

Most people serve more than one domain on their Cloud Server. Whether for different domain names or different subdomains of the same domain, the procedure is the same.

Our Linux Cloud Servers are built from a minimal installation image, meaning there are no additional applications installed beyond the base Operating System.

To begin using your server, you initiate an SSH session to remotely connect to the Cloud Server. In order to make it more useful, you are responsible for installing applications. This can be done by compiling a program from the source code, or more commonly using the Package Manager to install an application from a repository.

The most common application installed is a web server, such as Apache or Nginx.

In order to serve a website you must set up the rest of the framework to serve your content, and then upload the actual content to your server. This entails installing any databases or Content Management Systems your site requires. For networking, you will need to add appropriate DNS records in the Rackspace Cloud control panel, to let the DNS system and the rest of the Internet know that your site is hosted from a Rackspace Cloud IP address.

Finally, you come to the part that allows your Cloud Server to deliver your websites, and for this you will need to create your sites as virtual hosts within your webserver configuration.

Procedure

Greatly simplified, the procedure for serving a website is as follows:

A browser sends a request to your Cloud Server’s IP address asking for the contents of ‘http://yourexampledomain.com/’ (your domain name).

Your web server jumps into action and says “Yes! I have something for you matching your request”. The web server does its ‘thing’ and serves up an http representation of your site, which is sent to the requesting browser. The browser then translates the http and parses it to a human-readable form.

Simple, right? But how does your web server know what http to serve? If all you are serving is one website from the server, then it will serve the html in your /var/www/html directory, starting with index.html. We’ve all made a “Hello World” page before, right? But having a unique server for every website you want to serve is costly, and an inefficient use of your resources.

Virtual Hosts

Here come name based virtual hosts, allowing you to serve content for multiple websites from one server.

One of the first lines in any virtual host configuration file contains the domain name that is associated with the vhost.

This is a sample vhost configuration for Apache, serving domain1.com:

   <VirtualHost \*:80>        ServerName  domain1.com        ServerAlias www.domain1.com      </VirtualHost>

and this is a sample vhost configuration for Nginx:

   server {        server_name  www.domain1.com;        rewrite ^/(.\*) http://domain1.com/$1 permanent;

Each configuration starts slightly differently, but the same principle applies - that particular virtual host will respond to queries for ‘domain1.com’ and ‘www.domain1.com’.

Multiple domains

So, serving different content for different domains is as simple as adding another virtual host.

Let’s say you have a subdomain called ‘blog.domain1.com’ serving a blog.

The basic creation process would be to create a folder in your public_html folder with the relevant files (let’s say a Wordpress install).

A virtual host would be created with the server_name or ServerName as ‘blog.domain1.com’ which would be configured to point to the blog files and folders in your public_html folder.

Troubleshooting

This section shows you how to troubleshoot problems with Apache name-based virtual host configurations.

It will show you useful commands for testing your virtual host configuration, how to interpret their output, and how they help fix common virtual host configuration problems.

Restart Apache

Before we make a start on learning to diagnose your issue, make sure that you have restarted Apache since the last changes you made to your Apache configuration files:

If Apache gives you any warning or error message, make a note of it for the moment because we’re first going to take a look at a diagnostic command that’s used to check your virtual host configuration.

All the examples that follow assume you have created two virtual hosts: vh1.example.com and vh2.example.com.

We’re now ready to make a start, run the following command on the webserver:

Understanding the Configuration Report

The following example shows the configuration report for a server configured with two name-based virtual hosts.

       VirtualHost configuration:      wildcard NameVirtualHosts and \_default\_ servers:  [1] \*:80        is a NameVirtualHost [2] default server vh1.example.com (/etc/httpd/conf/custom/virtualhost.conf:3) [3] port 80 namevhost vh1.example.com (/etc/httpd/conf/custom/virtualhost.conf:3) [4] port 80 namevhost vh2.example.com (/etc/httpd/conf/custom/virtualhost.conf:8) [5] Syntax OK

[1] Reports that the webserver is listening on the default port of 80 for all the IP addresses that Apache is listening to, and that name-based virtual hosting is turned on. The * is a wildcard specifying all IP addresses.

[2] Reports the default virtual host the webserver will serve for any requests for which no specific hostname is requested. It also shows the path to the configuration file and line number where this configuration is set.

[3] Reports the port and the name of first virtual host configuration found, the file it is configured in and the line number its configuration starts on.

[4] Reports the port and the name of second virtual host configuration found, the file it is configured in and the line number its configuration starts on.

[5] Reports if the configuration syntax is correct, though that does not necessarily mean your site is working!

The output above was produced by the following virtual host file configuration:

   NameVirtualHost \*:80   Turns on name-based host resolution and binds the virtual server to IP addresses and ports as in [1] above. The \* is a wildcard specifying all IP addresses.  <VirtualHost \*:80>   Configures the first and default virtual host in [2] & [3] above. It is the default because it is the first virtual host whose IP and port matches those in the NameVirtualHost directive before it.   ServerName vh1.example.com   DocumentRoot /var/www/vhosts/vh1 </VirtualHost>  <VirtualHost \*:80>   Configures the second virtual host in [4] above.   ServerName vh2.example.com   DocumentRoot /var/www/vhosts/vh2 </VirtualHost>

Now that that you’ve seen how a basic virtual host configuration looks and how it maps to Apache’s own configuration report, let’s use those reports to look at common configuration issues.

Common Virtual Host Configuration Mistakes

This indicates that multiple virtual hosts are trying to use the same “socket” without being set up as name-based virtual hosts. This error often shows up on a first pass at creating Apache virtual hosts because the default NameVirtualHost directive is commented out with a hash. That hash instructs Apache to ignore the directive.

To fix this in a default Apache configuration file, you would check that the “NameVirtualHost *:80” directive is not commented out. If working with a minimal Apache configuration file, you would add a “NameVirtualHost *:80” directive prior to the individual virtual host configurations.

In the example below, we show the commented “NameVirtualHost *:80” directive that caused the above error:

   #NameVirtualHost \*:80  <VirtualHost \*:80>   ServerName vh1.example.com   DocumentRoot /var/www/vhosts/vh1 </VirtualHost>  <VirtualHost \*:80>   ServerName vh2.example.com   DocumentRoot /var/www/vhosts/vh2 </VirtualHost>

This means that the virtual host’s VirtualHost directive is missing a vital element. The VirtualHost is the first line of any individual virtual host configuration. In this case, it is on the 8th line of the configuration file /etc/httpd/conf/custom/virtualhost.conf.

Let’s review the Apache configuration that produced this above error:

   NameVirtualHost \*:80  <VirtualHost \*:80>   ServerName vh1.example.com   DocumentRoot /var/www/vhosts/vh1 </VirtualHost>  <VirtualHost>   ServerName vh2.example.com   DocumentRoot /var/www/vhosts/vh2 </VirtualHost>

Note how the directive has no IP address or port specified. That's the cause of our error.

Below is a corrected version of the above example. Notice the addition of “*:80” to the virtual host’s directive. As always, the \* is a wildcard specifying all IP addresses.

   NameVirtualHost \*:80  <VirtualHost \*:80>   ServerName vh1.example.com   DocumentRoot /var/www/vhosts/vh1 </VirtualHost>  <VirtualHost \*:80>   ServerName vh2.example.com   DocumentRoot /var/www/vhosts/vh2 </VirtualHost>

Note in the example above how the configuration test reports about vh2.example.com’s configuration before it reports the NameVirtualHost configuration. You may see this error if the VirtualHost IP address or port does not match that of a webserver’s NameVirtualHost directive. In this example, the test reports that vh2.example.com uses port 800 rather than the NameVirtualHost’s port 80. We mis-typed “80” when we configured the vh2.example.com virtual host’s listening port. As a result, Apache is seeing vh2.example.com as a separate port-based virtual host.

The test command “httpd -S” will not warn you about this because it is permissible to configure virtual hosts to use any port, such as 800, without their being part of the name-based virtual host configuration on the same server.

If you do make this mistake, you will probably see content from the default virtual host (vh1.example.com in this example) when you try to view the site in your web browser.

To help you map the above output to how its configuration file might look, here’s the virtual host configuration that created this error:

   NameVirtualHost \*:80  <VirtualHost \*:80>   ServerName vh1.example.com   DocumentRoot /var/www/vhosts/vh1 </VirtualHost>  <VirtualHost \*:800>   ServerName vh2.example.com   DocumentRoot /var/www/vhosts/vh2 </VirtualHost>

This specific error indicates that the directory specified as containing the website files for the vh2.example.com virtual host does not exist, or that Apache cannot access it. Similar errors can appear for any of the file paths specified in a virtual host configuration, such as the paths to the virtual host’s log files.

To fix, make sure you created the directory. If you definitely created it, check there are no mistakes in the DocumentRoot directive. A common mistake is to miss out the path’s initial “/”. Leaving out the “/” instructs Apache to read the path - the DocumentRoot path in this case - as a relative path. That is, as a path relative to the main Apache configuration’s ServerRoot path.

As there are several ways in which this error is often created, we’ve created an example of just one of them. In the example below, you’ll see that the path for the DocumentRoot in the first virtual host starts with a “/” but the second one does not. This makes Apache read the DocumentRoot path for vh2.example.com as an extension of the default webserver’s ServerRoot path /etc/httpd/ to create a DocumentRoot path of /etc/httpd/var/vhosts/vh2.

   ServerRoot /etc/httpd  NameVirtualHost \*:80  <VirtualHost \*:80>   ServerName vh1.example.com   DocumentRoot /var/www/vhosts/vh1 </VirtualHost>  <VirtualHost \*:80>   ServerName vh2.example.com   DocumentRoot var/www/vhosts/vh2 </VirtualHost>

Using Curl to Test Your Site

Once you’ve checked the virtual host configuration files and “httpd -S” reports no issues try to access your site using curl:

   curl -I www.example.com

The output should look something like this:

   HTTP/1.1 200 OK Date: Sat, 07 May 2011 15:09:50 GMT Server: Apache/2.2.3 (CentOS) Last-Modified: Mon, 25 Apr 2011 11:07:43 GMT ETag: "2c32e-77-4a1bc37723dc0" Accept-Ranges: bytes Content-Length: 119 Content-Type: text/html; charset=UTF-8

The first line shows the all-important status code. We want to see a “200 OK” as in the above line’s “HTTP/1.1 200 OK”. If that’s what you see, test the webserver with your browser, though be careful with this because you browser may be displaying a cached page.

If you don’t see “200 OK”, some of the common messages you may see are:

Check that your Apache configuration files include the necessary Listen directives and that they are not commented out. You’ll need “Listen 80” at the very least.

Check Error Log

Another way to look for this is check the error log. The default error log is at /var/log/httpd/error_log on Red Hat-derived systems and at /var/log/apache2/error_log on Debian-derived systems. You will see “no listening sockets available, shutting down” following Apache’s attempt to restart if you’re not specifying any port for Apache to listen on.

   [Mon May 09 21:50:21 2011] [notice] SIGHUP received.  Attempting to restart no listening sockets available, shutting down Unable to open logs

If you get this response when using curl it indicates the permissions aren’t quite right for allowing Apache access to the page you’re requesting. This could be because the directory permissions are incorrect or it could be the page itself.

You may also see a 403 error if the DocumentRoot contains no “index” file - typically named “index.html” or “index.php”. Note the filename is case sensitive. Or you may see 403s if the virtual host doesn’t contain a DirectoryIndex directive specifying the default index file.

The Apache error logs will usually reveal on which directory or file the permissions are incorrectly set. The default error log is at /var/log/httpd/error_log on Red Hat-derived systems and at /var/log/apache2/error_log on Debian-derived systems.

Individual virtual hosts may write errors to their own logs if they were configured to, so check these logs too.

Do not be put off by the volume of data in a busy server’s log files. Instead, use the “tail” command to selectively view just the most recent ten lines of a log. For example:

   tail /var/log/apache2/error\_log

Better yet, you can see new entries as they are added to the error_log - or any log - while you test the server if you instruct the “tail” command to “follow” the log. For example:

   tail -f /var/log/httpd/error\_log

Common Permissions-Related Errors

To round off our exploration of common Apache configuration errors, here are some examples of how some common permissions-related configuration errors appear in Apache’s logs

   [Sun May 15 20:06:17 2011] [error] [client 203.0.113.96] (13)Permission denied: file permissions deny server access: /var/www/vhosts/vh2/index.html

This log entry shows that permissions on the index.html file for vh2.example.com are denying access to Apache.

   [Sun May 15 20:07:37 2011] [error] [client 203.0.113.96] (13)Permission denied: access to /index.html denied

This log entry shows that permissions on the /var/www/vhosts/vh2 directory are blocking Apache’s read request.

   [Sun May 15 20:11:32 2011] [error] [client 203.0.113.96] (13)Permission denied: access to / denied

This log entry shows that Apache does not have execute or read permissions on one of the directories above DocumentRoot.

##########################################################################################################

Apache Virtual Hosting: IP Based and Name Based Virtual Hosts in RHEL/CentOS/Fedora

by Tarunika Shrivastava | Published: January 6, 2014 | Last Updated: November 25, 2015

 Download Your Free eBooks NOW - 10 Free Linux eBooks for Administrators | 4 Free Shell Scripting eBooks

As we all are aware that Apache is a very powerful, highly flexible and configurable Web server for Nix OS. Here in this tutorial, we are going to discuss one more feature of Apache which allows us to host more than one website on a single Linux machine. Implementing virtual hosting with Apache web server can help you to save costs you are investing on your server maintenance and their administration.

Don’t Miss: NGINX Name-based and IP-based Virtual Hosting (Server Blocks)

--------------

Apache Virtual Hosting in Linux

Concept of Shared web hosting and Reseller web hosting is based on this facility of Apache only.

Types of Virtual Host

There are two types of virtual hosting is available with Apache.

Name Based Virtual Hosting

With the name based virtual hosting you can host several domains/websites on a single machine with a single IP. All domains on that server will be sharing a single IP. It’s easier to configure than IP based virtual hosting, you only need to configure DNS of the domain to map it with its correct IP address and then configure Apache to recognize it with the domain names.

Name Based Virtual Hosting

IP Based Virtual Hosting

With the IP based virtual hosting, you can assign a separate IP for each domain on a single server, these IP’s can be attached to the server with single NIC cards and as well as multiple NICs.

IP Based Virtual Hosting

Lets set up Name Based Virtual Hosting and IP based Virtual hosting in RHEL, CentOS and Fedora.

Testing Environment

How to Setup IP Based and Name Based Apache Virtual Hosts

Before setting up virtual hosting with Apache, your system must have Apache Web software installed. if not, install it using default package installer called yum.

[root@tecmint ~]# yum install httpd

Setup Name Based Virtual Host

But, before creating a virtual host, you need to create a directory where you will keep all your website’s files. So, create directories for these two virtual hosts under /var/www/html folder. Please remember/var/www/html will be your default Document Root in the Apache virtual configuration.

[root@tecmint ~]# mkdir /var/www/html/example1.com/ [root@tecmint ~]# mkdir /var/www/html/example2.com/

To set up Name based virtual hosting you must need to tell Apache to which IP you will be using to receive the Apache requests for all the websites or domain names. We can do this withNameVirtualHost directive. Open Apache main configuration file with VI editor.

[root@tecmint ~]# vi /etc/httpd/conf/httpd.conf

Search for NameVirtualHost and uncomment this line by removing the # sign in front of it.

NameVirtualHost

Next add the IP with possible in which you want to receive Apache requests. After the changes, your file should look like this:

NameVirtualHost 192.168.0.100:80

Now, it’s time to setup Virtual host sections for your domains, move to the bottom of the file by pressingShift + G. Here in this example, We are setting up virtual host sections for two domains

Add the following two virtual directives at the bottom of the file. Save and close the file.

<VirtualHost 192.168.0.100:80>     ServerAdmin webmaster@example1.com     DocumentRoot /var/www/html/example1.com     ServerName www.example1.com ErrorLog logs/www.example1.com-error_log CustomLog logs/www.example1.com-access_log common </VirtualHost>  <VirtualHost *:80>     ServerAdmin webmaster@example2.com     DocumentRoot /var/www/html/example2.com     ServerName www.example2.com ErrorLog logs/www.example2.com-error_log CustomLog logs/www.example2.com-access_log common </VirtualHost>

You are free to add as many directives you want to add in your domains virtual host section. When you are done with changes in httpd.conf file, please check the syntax of files with following command.

[root@tecmint ~]# httpd -t  Syntax OK

It is recommended to check the syntax of the file after making some changes and before restarting the Web server because if any syntax goes wrong Apache will refuse to work with some errors and eventually affect your existing web server go down for a while. If syntax is OK. Please restart your Web server and add it to chkconfig to make your web server start in runlevel 3 and 5 at the boot time only.

[root@tecmint ~]# service httpd restart Stopping httpd:                                            [  OK  ] Starting httpd:                                            [  OK  ]

[root@tecmint ~]# chkconfig --level 35 httpd on

Now it’s time to create a test page called index.html add some content to the file so we will have something to check it, when the IP calls the virtual host.

[root@tecmint ~]# vi /var/www/html/example1.com/index.html

<html>   <head>     <title>www.example1.com</title>   </head>   <body>     <h1>Hello, Welcome to www.example1.com.</h1>   </body> </html>

[root@tecmint ~]# vi /var/www/html/example2.com/index.html

<html>   <head>     <title>www.example2.com</title>   </head>   <body>     <h1>Hello, Welcome to www.example2.com.</h1>   </body> </html>

Once you’re done with it, you can test the setup by accessing both the domains in a browser.

http://www.example1.com http://www.example2.com

Preview: www.example1.com

Virtual Hosting: www.example1.com

Preview: www.example2.com

Virtual Hosting: www.example2.com

Setup IP Based Virtual Hosting Linux

To setup IP based virtual hosting, you must have more than one IP address/Port assigned to your server or your Linux machine.

It can be on a single NIC card , For example: eth0:1, eth0:2, eth0:3 … so forth. Multiple NIC cards can also be attached. If you don’t know how to create multiple IP’s on single NIC, follow the below guide, that will help you out in creating.

Purpose of implementing IP based virtual hosting is to assign implementing for each domain and that particular IP will not be used by any other domain.

This kind of set up required when a website is running with SSL certificate (mod_ssl) or on different ports and IPs. And You can also run multiple instances of Apache on a single machine. To check the IPs attached in your server, please check it using ifconfig command.

root@tecmint ~]# ifconfig

Sample Output

 eth0      Link encap:Ethernet  HWaddr 08:00:27:4C:EB:CE             inet addr:192.168.0.100  Bcast:192.168.0.255  Mask:255.255.255.0           inet6 addr: fe80::a00:27ff:fe4c:ebce/64 Scope:Link           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1           RX packets:17550 errors:0 dropped:0 overruns:0 frame:0           TX packets:15120 errors:0 dropped:0 overruns:0 carrier:0           collisions:0 txqueuelen:1000           RX bytes:16565983 (15.7 MiB)  TX bytes:2409604 (2.2 MiB)  eth0:1    Link encap:Ethernet  HWaddr 08:00:27:4C:EB:CE             inet addr:192.168.0.101  Bcast:192.168.0.255  Mask:255.255.255.0           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1  lo        Link encap:Local Loopback             inet addr:127.0.0.1  Mask:255.0.0.0           inet6 addr: ::1/128 Scope:Host           UP LOOPBACK RUNNING  MTU:16436  Metric:1           RX packets:1775 errors:0 dropped:0 overruns:0 frame:0           TX packets:1775 errors:0 dropped:0 overruns:0 carrier:0           collisions:0 txqueuelen:0           RX bytes:3416104 (3.2 MiB)  TX bytes:3416104 (3.2 MiB)

As you can see in above output, two IPs 192.168.0.100 (eth0) and 192.168.0.101 (eth0:1) is attached to the server, both IPs are assigned to the same physical network device (eth0).

Now, assign a specific IP/Port to receive http requests, you can simply do it by changing Listen directive in httpd.conf file.

[root@tecmint ~]# vi /etc/httpd/conf/httpd.conf

Search for word “Listen”, You find a section where the short description about Listen directive is written. In that section, comment the original line and write your own directive below that line.

# Listen 80  Listen 192.168.0.100:80

Now,  create a Virtual host sections for both the domains. Go the bottom of the file and add the following virtual directives.

VirtualHost 192.168.0.100:80>     ServerAdmin webmaster@example1.com     DocumentRoot /var/www/html/example1     ServerName www.example1.com ErrorLog logs/www.example1.com-error_log TransferLog logs/www.example1.com-access_log </VirtualHost>  <VirtualHost 192.168.0.101:80>     ServerAdmin webmaster@example2.com     DocumentRoot /var/www/html/example2     ServerName www.example2.com ErrorLog logs/www.example2.com-error_log TransferLog logs/www.example2.com-access_log </VirtualHost>

Now, since you have modified main Apache conf file, you need to restart the http service like below.

[root@tecmint ~]# service httpd restart Stopping httpd:                                            [  OK  ] Starting httpd:                                            [  OK  ]

Test your IP based Virtual hosting setup by accessing the URLs on web browser as shown below.

http://www.example1.com http://www.example2.com

That’s all with Apache virtual host today, If you’re looking to secure and harden your Apache configuration, then read our article that guides.

Reference Links

Apache Virtual Host Documentation

I’ll be again come with some other Apache tips and trick in my future articles, till then Stay Geeky and connected to Tecmint.com. Do not forget to leave your suggestions about the article in our comment section below.

###########################################################################################

How To Set Up Apache Virtual Hosts on CentOS 6

Jun 3, 2012  Apache CentOS

About Virtual Hosts

Virtual Hosts are used to run more than one domain off of a single IP address. This is especially useful to people who need to run several sites off of one virtual private server. The sites display different information to the visitors, depending on with which the users accessed the site.There is no limit to the number of virtual hosts that can be added to a VPS.

Set Up

The steps in this tutorial require the user to have root privileges. You can see how to set that up in theInitial Server Setup in steps 3 and 4. Furthermore, if I reference the user in a step, I’ll use the name www. You can implement whatever username suits you.

Additionally, you need to have apache already installed and running on your virtual server If this is not the case, you can download it with this command:

sudo yum install httpd

Step One— Create a New Directory

The first step in creating a virtual host is to a create a directory where we will keep the new website’s information.

This location will be your Document Root in the Apache virtual configuration file later on. By adding a -p to the line of code, the command automatically generates all the parents for the new directory.

sudo mkdir -p /var/www/example.com/public_html

You will need to designate an actual DNS approved domain, or an IP address, to test that a virtual host is working. In this tutorial we will use example.com as a placeholder for a correct domain name.

However, should you want to use an unapproved domain name to test the process you will find information on how to make it work on your local computer in Step Six.

Step Two—Grant Permissions

We need to grant ownership of the directory to the user, instead of just keeping it on the root system.

sudo chown -R apache:apache /var/www/example.com/public_html

Additionally, it is important to make sure that everyone will be able to read our new files.

sudo chmod 755 /var/www

Now you are all done with permissions.

Step Three— Create the Page

We need to create a new file called index.html within our configurations directory.

sudo vi /var/www/example.com/public_html/index.html

We can add some text to the file so we will have something to look at when the IP redirects to the virtual host.

<html>   <head>     <title>www.example.com</title>   </head>   <body>     <h1>Success: You Have Set Up a Virtual Host</h1>   </body> </html>

Save and Exit

Step Four—Turn on Virtual Hosts

The next step is to enter into the apache configuration file itself.

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

There are a few lines to look for.

Make sure that your text matches what you see below.

#Listen 12.34.56.78:80 Listen 80

Scroll down to the very bottom of the document to the section called Virtual Hosts.

NameVirtualHost *:80 # # NOTE: NameVirtualHost cannot be used without a port specifier # (e.g. :80) if mod_ssl is being used, due to the nature of the # SSL protocol. #      #     # VirtualHost example: # Almost any Apache directive may go into a VirtualHost container. # The first VirtualHost section is used for requests without a known # server name. #  <VirtualHost *:80>      ServerAdmin webmaster@example.com      DocumentRoot /var/www/example.com/public_html      ServerName www.example.com      ServerAlias example.com      ErrorLog /var/www/example.com/error.log      CustomLog /var/www/example.com/requests.log </VirtualHost>

The most important lines to focus on are the lines that say NameVirtualHost, Virtual Host, Document Root, and Server Name. Let’s take these one at a time.

The rest of the lines in this section are not required to set up a virtual host. However, it is still helpful to know what they do.

Step Five—Restart Apache

We’ve made a lot of the changes to the configuration. However, they will not take effect until Apache is restarted.

First stop all apache processes:

sudo apachectl -k stop

Then start up apache once again.

sudo /etc/init.d/httpd start

You may see the following error:

Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

The message is just a warning, and you will be able to access your virtual host without any further issues.

Optional Step Six—Setting Up the Local Hosts

If you have pointed your domain name to your virtual private server’s IP address you can skip this step—you do not need to set up local hosts. Your virtual hosts should work. However, if want to try out your new virtual hosts without having to connect to an actual domain name, you can set up local hosts on your computer alone. For this step, make sure you are on the computer itself, not your droplet.

To proceed with this step you need to know your computer’s administrative password, otherwise you will be required to use an actual domain name to test the virtual hosts.

If you are on a Mac or Linux, access the root user (su) on the computer and open up your hosts file:

nano /etc/hosts

If you are on a Windows Computer, you can find the directions to alter the host file on the Microsoft site

You can add the local hosts details to this file, as seen in the example below. As long as that line is there, directing your browser toward, say, example.com will give you all the virtual host details for the corresponding IP address.

# Host Database # # localhost is used to configure the loopback interface # when the system is booting.  Do not change this entry. ## 127.0.0.1       localhost  #Virtual Hosts  12.34.56.789    www.example.com

However, it may be a good idea to delete these made up addresses out of the local hosts folder when you are done to avoid any future confusion.

Step Seven—RESULTS: See Your Virtual Host in Action

Once you have finished setting up your virtual host, you can see how it looks online. Type your ip address into the browser (ie. http://12.34.56.789)

It should look somewhat similar to my handy screenshot

Good Job!

Adding More Virtual Hosts

To create additional virtual hosts, you can just repeat the process above, being careful to set up a new document root with the appropriate new domain name each time. Then just copy and paste the new Virtual Host information into the Apache Config file, as shown below

<VirtualHost *:80>      ServerAdmin webmaster@example.com      DocumentRoot /var/www/example.com/public_html      ServerName www.example.com      ServerAlias example.com      ErrorLog /etc/var/www/example.com/error.log      CustomLog /var/www/example.com/requests.log </VirtualHost> <VirtualHost *:80>      ServerAdmin webmaster@example.org      DocumentRoot /var/www/example.org/public_html      ServerName www.example.org      ServerAlias example.org      ErrorLog /var/www/example.org/error.log      CustomLog /var/www/example.orgrequests.log </VirtualHost>

See More

Once you have set up your virtual hosts, you can proceed to Create a SSL Certificate for your site or Install an FTP server

By Etel Sverdlov

################################################################################