Tuesday, November 25, 2014

Linux Firewall Tutorial: IPTables Tables, Chains, Rules Fundamentals

iptables firewall is used to manage packet filtering and NAT rules. IPTables comes with all Linux distributions. Understanding how to setup and configure iptables will help you manage your Linux firewall effectively.
iptables tool is used to manage the Linux firewall rules. At a first look, iptables might look complex (or even confusing). But, once you understand the basics of how iptables work and how it is structured, reading and writing iptables firewall rules will be easy.
This article is part of an ongoing iptables tutorial series. This is the 1st article in that series.
This article explains how iptables is structured, and explains the fundamentals about iptables tables, chains and rules.

On a high-level iptables might contain multiple tables. Tables might contain multiple chains. Chains can be built-in or user-defined. Chains might contain multiple rules. Rules are defined for the packets.
So, the structure is: iptables -> Tables -> Chains -> Rules. This is defined in the following diagram.

Fig: IPTables Table, Chain, and Rule Structure
Just to re-iterate, tables are bunch of chains, and chains are bunch of firewall rules.

I. IPTABLES TABLES and CHAINS

IPTables has the following 4 built-in tables.

1. Filter Table

Filter is default table for iptables. So, if you don’t define you own table, you’ll be using filter table. Iptables’s filter table has the following built-in chains.
  • INPUT chain – Incoming to firewall. For packets coming to the local server.
  • OUTPUT chain – Outgoing from firewall. For packets generated locally and going out of the local server.
  • FORWARD chain – Packet for another NIC on the local server. For packets routed through the local server.

2. NAT table

Iptable’s NAT table has the following built-in chains.
  • PREROUTING chain – Alters packets before routing. i.e Packet translation happens immediately after the packet comes to the system (and before routing). This helps to translate the destination ip address of the packets to something that matches the routing on the local server. This is used for DNAT (destination NAT).
  • POSTROUTING chain – Alters packets after routing. i.e Packet translation happens when the packets are leaving the system. This helps to translate the source ip address of the packets to something that might match the routing on the desintation server. This is used for SNAT (source NAT).
  • OUTPUT chain – NAT for locally generated packets on the firewall.

3. Mangle table

Iptables’s Mangle table is for specialized packet alteration. This alters QOS bits in the TCP header. Mangle table has the following built-in chains.
  • PREROUTING chain
  • OUTPUT chain
  • FORWARD chain
  • INPUT chain
  • POSTROUTING chain

4. Raw table

Iptable’s Raw table is for configuration excemptions. Raw table has the following built-in chains.
  • PREROUTING chain
  • OUTPUT chain
The following diagram shows the three important tables in iptables.

Fig: IPTables built-in tables

II. IPTABLES RULES

Following are the key points to remember for the iptables rules.
  • Rules contain a criteria and a target.
  • If the criteria is matched, it goes to the rules specified in the target (or) executes the special values mentioned in the target.
  • If the criteria is not matached, it moves on to the next rule.

Target Values

Following are the possible special values that you can specify in the target.
  • ACCEPT – Firewall will accept the packet.
  • DROP – Firewall will drop the packet.
  • QUEUE – Firewall will pass the packet to the userspace.
  • RETURN – Firewall will stop executing the next set of rules in the current chain for this packet. The control will be returned to the calling chain.
If you do iptables –list (or) service iptables status, you’ll see all the available firewall rules on your system. The following iptable example shows that there are no firewall rules defined on this system. As you see, it displays the default input table, with the default input chain, forward chain, and output chain.
# iptables -t filter --list
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
Do the following to view the mangle table.
# iptables -t mangle --list
Do the following to view the nat table.
# iptables -t nat --list
Do the following to view the raw table.
# iptables -t raw --list
Note: If you don’t specify the -t option, it will display the default filter table. So, both of the following commands are the same.
# iptables -t filter --list
(or)
# iptables --list
The following iptable example shows that there are some rules defined in the input, forward, and output chain of the filter table.
# iptables --list
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    RH-Firewall-1-INPUT  all  --  0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination
1    RH-Firewall-1-INPUT  all  --  0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination

Chain RH-Firewall-1-INPUT (2 references)
num  target     prot opt source               destination
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           icmp type 255
3    ACCEPT     esp  --  0.0.0.0/0            0.0.0.0/0
4    ACCEPT     ah   --  0.0.0.0/0            0.0.0.0/0
5    ACCEPT     udp  --  0.0.0.0/0            224.0.0.251         udp dpt:5353
6    ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0           udp dpt:631
7    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:631
8    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
9    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
10   REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited
The rules in the iptables –list command output contains the following fields:
  • num – Rule number within the particular chain
  • target – Special target variable that we discussed above
  • prot – Protocols. tcp, udp, icmp, etc.,
  • opt – Special options for that specific rule.
  • source – Source ip-address of the packet
  • destination – Destination ip-address for the packet

Ubuntu Tips: How To Use Windows Applications in Linux Desktop Distributions

Question: How to run Windows applications in Ubuntu or any other Linux desktop distribution ?
Answer: Install wine project, which will enable you to use Windows applications in Linux systems.

What is Wine ?

Using Wine you can execute Windows application like Microsoft Word, Excel, PowerPoint etc., in your Linux.  Currently, 12,000+ Windows applications can run in Ubuntu with Wine.

How To Install Wine in Ubuntu ?

Wine is a pretty big package which may take some time for the installation to complete, especially if you are on a slower internet connection.
$ sudo apt-get install wine

How to Install Your Favorite Windows Application ?

You can install Wine using one of the following two methods.

Method 1: Default Installation

Search and download the wine compatible Windows application from WineHQ website.
  1. Go to winehq.org
  2. Select AppDB in the top menu
  3. Select the Browse Apps in the left side bar
Locate and download the required application. Double click on that downloaded application, which should let you use the application. If it gives any one of the following error messages, go to Method 2 to install it again.
  • Unable to find volume for extraction
  • Permission denied
Every application has a rating available to it.  For example, if it has Platinum rating, you should not have any issues with the default installation. Maintainer Ratings definition gives information about all available ratings.

Method 2: Install Using Winetricks

Install cabextract: Cabextract is required by winetricks.
$ sudo apt-get install cabextract
Install winetricks: Download the latest winetricks.
$ wget http://winezeug.googlecode.com/svn/trunk/winetricks
Launch winetricks as shown below. The following example will install Microsoft Internet Explorer on Linux.
$ sh winetricks ie6
The following images shows Microsoft Internet Explorer browser on Ubuntu Laptop.

How To Install Java JDK or JRE on Ubuntu or Debian

Question: How do I Install Java on Ubuntu or Debian OS?
Answer: If Java is not installed, you’ll get the following error message when you do java -version.

# java -version
The program 'java' can be found in the following packages:
 * gij-4.3
 * java-gcj-compat-headless
 * openjdk-6-jre-headless
 * cacao
 * gij-4.2
 * jamvm
 * kaffe
Try: apt-get install

-su: java: command not found

Search for Java Package that needs to be Installed

Before installing, you may want to do apt-cache search to find out all available packages that starts with sun-java.
As shown below, you’ll find both Java5 and Java6 JDK and JRE related packages.
# sudo apt-get update

# apt-cache search ^sun-java
sun-javadb-client - Java DB client
sun-javadb-common - Java DB common files
sun-javadb-core - Java DB core
sun-javadb-demo - Java DB demo
sun-javadb-doc - Java DB documentation
sun-javadb-javadoc - Java DB javadoc
sun-java5-bin - Sun Java(TM) Runtime Environment (JRE) 5.0 (architecture dependent files)
sun-java5-demo - Sun Java(TM) Development Kit (JDK) 5.0 demos and examples
sun-java5-doc - Sun JDK(TM) Documention -- integration installer
sun-java5-fonts - Lucida TrueType fonts (from the Sun JRE)
sun-java5-jdk - Sun Java(TM) Development Kit (JDK) 5.0
sun-java5-jre - Sun Java(TM) Runtime Environment (JRE) 5.0 (architecture independent files)
sun-java5-plugin - The Java(TM) Plug-in, Java SE 5.0
sun-java5-source - Sun Java(TM) Development Kit (JDK) 5.0 source files
sun-java6-bin - Sun Java(TM) Runtime Environment (JRE) 6 (architecture dependent files)
sun-java6-demo - Sun Java(TM) Development Kit (JDK) 6 demos and examples
sun-java6-doc - Sun JDK(TM) Documention -- integration installer
sun-java6-fonts - Lucida TrueType fonts (from the Sun JRE)
sun-java6-javadb - Java(TM) DB, Sun Microsystems' distribution of Apache Derby
sun-java6-jdk - Sun Java(TM) Development Kit (JDK) 6
sun-java6-jre - Sun Java(TM) Runtime Environment (JRE) 6 (architecture independent files)
sun-java6-plugin - The Java(TM) Plug-in, Java SE 6
sun-java6-source - Sun Java(TM) Development Kit (JDK) 6 source files

Install Java on Ubuntu

Execute sudo apt-get install sun-java6-jdk to install the Java 6 JDK on Ubuntu as shown below. If you need only the run time environment, install sun-java6-jre.
# sudo apt-get install sun-java6-jdk
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  linux-headers-2.6.28-11 linux-headers-2.6.28-11-generic
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  gsfonts-x11 java-common odbcinst1debian1 sun-java6-bin sun-java6-jre unixodbc
Suggested packages:
  equivs sun-java6-demo openjdk-6-doc sun-java6-source sun-java6-plugin ia32-sun-java6-plugin sun-java6-fonts
  libmyodbc odbc-postgresql libct1
The following NEW packages will be installed:
  gsfonts-x11 java-common odbcinst1debian1 sun-java6-bin sun-java6-jdk sun-java6-jre unixodbc
0 upgraded, 7 newly installed, 0 to remove and 68 not upgraded.
Need to get 54.5MB of archives.
After this operation, 161MB of additional disk space will be used.
Do you want to continue [Y/n]? Y
Get:1 http://us.archive.ubuntu.com jaunty/main java-common 0.30ubuntu4 [80.3kB]
Get:2 http://us.archive.ubuntu.com jaunty-updates/multiverse sun-java6-jre 6-16-0ubuntu1.9.04 [6421kB]
Get:3 http://us.archive.ubuntu.com jaunty/main odbcinst1debian1 2.2.11-16build3 [66.3kB]
Get:4 http://us.archive.ubuntu.com jaunty/main unixodbc 2.2.11-16build3 [295kB]
Get:5 http://us.archive.ubuntu.com jaunty-updates/multiverse sun-java6-bin 6-16-0ubuntu1.9.04 [29.1MB]
Get:6 http://us.archive.ubuntu.com jaunty-updates/multiverse sun-java6-jdk 6-16-0ubuntu1.9.04 [18.5MB]
Get:7 http://us.archive.ubuntu.com jaunty/main gsfonts-x11 0.21 [10.5kB]
Fetched 54.5MB in 4min 53s (186kB/s)
Preconfiguring packages ...
Selecting previously deselected package java-common.
(Reading database ... 142715 files and directories currently installed.)
Unpacking java-common (from .../java-common_0.30ubuntu4_all.deb) ...
Selecting previously deselected package sun-java6-jre.
Unpacking sun-java6-jre (from .../sun-java6-jre_6-16-0ubuntu1.9.04_all.deb) ...
Selecting previously deselected package odbcinst1debian1.
Unpacking odbcinst1debian1 (from .../odbcinst1debian1_2.2.11-16build3_i386.deb) ...
Selecting previously deselected package unixodbc.
Unpacking unixodbc (from .../unixodbc_2.2.11-16build3_i386.deb) ...
Selecting previously deselected package sun-java6-bin.
Unpacking sun-java6-bin (from .../sun-java6-bin_6-16-0ubuntu1.9.04_i386.deb) ...
sun-dlj-v1-1 license has already been accepted
Selecting previously deselected package sun-java6-jdk.
Unpacking sun-java6-jdk (from .../sun-java6-jdk_6-16-0ubuntu1.9.04_i386.deb) ...
sun-dlj-v1-1 license has already been accepted
Selecting previously deselected package gsfonts-x11.
Unpacking gsfonts-x11 (from .../gsfonts-x11_0.21_all.deb) ...
Processing triggers for doc-base ...
Processing 3 added doc-base file(s)...
Registering documents with scrollkeeper...
Processing triggers for man-db ...
Processing triggers for shared-mime-info ...
Setting up java-common (0.30ubuntu4) ...
Setting up odbcinst1debian1 (2.2.11-16build3) ...
Setting up unixodbc (2.2.11-16build3) ...
Setting up gsfonts-x11 (0.21) ...
Setting up sun-java6-bin (6-16-0ubuntu1.9.04) ...
Setting up sun-java6-jre (6-16-0ubuntu1.9.04) ...
Setting up sun-java6-jdk (6-16-0ubuntu1.9.04) ...
Processing triggers for libc6 ...
ldconfig deferred processing now taking place
During the installation, you’ll be prompted with the following window, where you have to read the “Operating System Distributor License for Java” and click on OK.
Fig: Sun Java License Terms - Click OK
Fig: Sun Java License Terms - Click OK
After reading the license terms, you’ll be prompted with the following window, where you have to agree to the “license terms” by clicking on Yes.
Fig: Accept Java JDK/JRE License Terms - Click Yes
Fig: Accept Java JDK/JRE License Terms - Click Yes

Verify the Java Installation

Finally, execute java -version and make sure Java is installed properly as shown below.
# java -version
java version "1.6.0_16"
Java(TM) SE Runtime Environment (build 1.6.0_16-b01)
Java HotSpot(TM) Server VM (build 14.2-b01, mixed mode)

Ubuntu Tips: How To View System Log Files in GUI

Question: When debugging an issue on Ubuntu, I typically go to the command line to view the log file. Are there any GUI log file viewers available for Ubuntu?
Answer: Ubuntu comes with an inbuilt system log file viewer.

Launching System Log Viewer

Click on System -> Administration -> Log File Viewer, to launch the GUI log viewer tool.
The example below shows the auth.log file contents. This is a real time log file viewer. When you are viewing a log file, if there are any new log entries, they’ll be displayed immediately. The newer entries will be shown in bold as shown in the following example.
Ubuntu System Log Viewer User Interface
Fig: Ubuntu System Log Viewer

Updated Log Files will be shown in bold

When you are viewing a file, if there are newer entries available on other log files, they’ll be displayed in bold. In the following example, the current file we are viewing is user.log.0. However, the syslog file is in bold indicating that there is a newer log entry available in it.
Ubuntu System Log File Viewer - Real Time Log Updates
Fig: Ubuntu System Log Viewer – with real time file updates

Adding Custom Log Files to the Viewer.

By default Ubuntu System Log Viewer shows all important system log files including the following:
  • auth.log
  • boot
  • debug
  • dmesg
  • dpkg.log
  • kern.log
  • mail.log
  • messages
  • syslog
However you can add your own custom log to this list. From the System Log Viewer, click on File -> Open -> Select the log file using file browser. In this example, we are selecting the /var/log/apache2/error.log.
Ubuntu System Log Viewer - Open Custom Log File
Fig: Open a Custom Log File
Once you’ve added the custom log file, even after you close and open the System Log Viewer, it will be there. To remove a log file permanently from the System Log Viewer, select the log file -> Click on File -> Remove.
Ubuntu System Log Viewer showing Apache Error Log

How to Convert Text Document to Speech on Ubuntu Using eSpeak

Ubuntu espeak is a speech synthesizer for English (and several other languages) which will convert text to speech.
You can straight away execute espeak command on your Ubuntu machine without any installation or configuration.
In this article, let us review 8 examples of espeak command.

espeak Example 1: Speak the words specified in command line

This is the default usage.
# espeak --stdout 'words to speak' | aplay
Note: The above may also display the following message: “Playing WAVE ‘stdin’ : Signed 16 bit Little Endian, Rate 22050 Hz, Mono”

espeak Example 2: Speak the words specified in stdin

This will take the words interactively from the standard input and convert it to speech.
# espeak --stdout | aplay

espeak Example 3: Speak your document

This will convert the text from the mydocument.txt to speech.
# espeak --stdout -t mydocument.txt | aplay

espeak Example 4: Generate voice file from text document

Convert your text file to an audio file as shown below.
# espeak -t mydocument.txt -w myaudio.wav

Customizing espeak

If you find the default speech synthesizing is not good, you can try to customize it as explained below.

espeak Example 5: List all available voice languages

# espeak --voices
Pty Language Age/Gender VoiceName       File        Other Langs
 5  af             M  afrikaans         af
 5  bs             M  bosnian           bs
 5  ca             M  catalan           ca
 5  cs             M  czech             cs
 5  cy             M  welsh-test        cy
 5  de             M  german            de
 5  el             M  greek             el
 5  en             M  default           default
 5  en-sc          M  en-scottish       en/en-sc    (en 4)
.......

espeak Example 6: Choose a different voice language

The following will use “en-uk” – British english to translate the text to speech.
# espeak -v en-uk --stdout 'reading tips & tricks in TGS' | aplay

espeak Example 7: Increase or Decrease the number of spoken words per minute.

The default is 160 words per minute. You can reduce it using option -s as shown below.
# espeak -s 140 -f mydocument.txt | aplay

espeak Example 8: List the available espeak voices in specific language

The following example will display all possible english language variation that you can use for your text to speech conversion.
# espeak --voice=en
Pty Language Age/Gender VoiceName       File        Other Langs
 2  en-uk          M  english           en/en       (en 2)
 3  en-uk          M  english-mb-en1    mb/mb-en1   (en 2)
 2  en-us          M  english-us        en/en-us    (en-r 5)(en 3)
 5  en-sc          M  en-scottish       en/en-sc    (en 4)
 5  en             M  default           default
.....

7zip File: How to Uncompress 7z files on Ubuntu, Debian, Fedora

Question: How do I uncompress a *.7z file ( 7zip file ) in UNIX / Linux ? Can you explain with a simple example?
Answer: Use 7za command to unzip a 7z file ( 7zip file ) on Unix platform as shown below.

Verify whether you have 7za command on your system.
# whereis 7za
7za: /usr/bin/7za /usr/share/man/man1/7za.1.gz
If you don’t have 7za command, install p7zip package as shown below.

Install p7zip to unzip *.7z files on Fedora

# yum install p7zip

Install p7zip to unzip *.7z files on Debian and Ubuntu

$ sudo apt-get install p7zip

Uncompressing a *.7z 7zip files in Linux using 7za

$ 7za e myfiles.7z 

7-Zip (A) 9.04 beta  Copyright (c) 1999-2009 Igor Pavlov  2009-05-30
p7zip Version 9.04 (locale=C,Utf16=off,HugeFiles=on,1 CPU)

Processing archive: ../../myfiles.7z

Extracting  myfiles/test1
Extracting  myfiles/test2
Extracting  myfiles/test
Extracting  myfiles

Everything is Ok

Folders: 1
Files: 3
Size:       7880
Compressed: 404
  • 7za – command name
  • e – specifies the 7z to be extracted
  • myfiles.7z – is the file that is to be extracted

Creating a 7zip compression file in Linux

$ 7za a myfiles.7z myfiles/

7-Zip (A) 9.04 beta  Copyright (c) 1999-2009 Igor Pavlov  2009-05-30
p7zip Version 9.04 (locale=C,Utf16=off,HugeFiles=on,1 CPU)
Scanning

Creating archive myfiles.7z

Compressing  myfiles/test1
Compressing  myfiles/test2      

Everything is Ok
Files and sub directories of myfiles/ will be added to the myfiles.7z.
  • a – add to archive
  • file.7z – archive file to which these files and dir from dir1 will be added to.

4 Methods to Take Screenshot Capture in Ubuntu Linux

Screenshot is an image taken by a computer to capture the visible items on the monitor or any other output devices. There are several ways of taking screenshots in Linux. In this article, we will cover few tools that are used for taking screenshots.

1. Use Print Screen

This is the most common method to take screenshots. Pressing the “Print Screen” button will take the screenshot of the “Entire Visible Screen”.
When we want to take a particular window, we can use “Alt+Print Screen”. Alt+PrintScreen will take only the particular window which is currently active.

2. Use gnome-screenshot

gnome-screenshot utility is part of the GNOME Desktop Environment, which can also be used to take screenshot. It also has a command line mode (gnome-screenshot)
Launch the screenshot tool as shown below.


Capture the Entire Screen:

From the UI, to take a screenshot with entire screen, select “Grab the whole desktop” and click “Take Screenshot”.
From the command-line, just type the command “gnome-screenshot” to do the same. The command will take a screenshot and provide a dialog to save it.
$ gnome-screenshot

Capture Only the Current Window:

From the UI, to take the screenshot of the current active window alone, select “Grab the Current Window” and click “Take Screenshot”.
From the command-line, use the -w option as follows to do the same.
$ gnome-screenshot -w

Take Screenshot After Some Delay:

From the UI, you can also set a delay before taking the screenshots. Set the “Grab after a delay” to the required number of seconds. This will be really helpful when we need to take screen shots of navigation.
From the command-line, use -d option to do the same. -d 2 is used for delaying the screenshot for 2 seconds. So within the 2 seconds, we can make the window which we want to take screenshot as active.
$ gnome-screenshot -w -d 2

Capture a Particular Area:

From the UI, if you want to take a particular rectangle area alone, then select “Grab a Particular area” and click “Take Screenshot”.
From the command-line, use the -a option to do the same. Once this command is entered, the mouse pointer will be changed, and you can drag and select which area to take screenshot.
$ gnome-screenshot -a

Take Screenshot Including or Excluding Window Border:

From the UI, you can also include or exclude the window border by selecting/deselecting “Include the Window Border” option.
From the command line, use -b/-B options respectively to do the same. This command will include the window border along with the screenshot.
$ gnome-screenshot -w -b
The following command will exclude the window border from the screenshot.
$ gnome-screenshot -w -B

3. Use ImageMagic’s Import Command

ImageMagick is an open source software suite for displaying, converting, and editing raster image files. It comes with various command line tools, and one of that is “import”. Now we will see, how we can use import to take screenshots. You can install it by using apt-get on debian/ubuntu as follows:
# apt-get install imagemagick

Capture Entire Screen using -window root option

Use the “-window root” option to take screenshot of the complete screen. The screenshot will be saved in the file name provided in the command line.
$ import -window root Pictures/Image5.png
ImageMagick supports more that 100 file types. You can use any one of them to store the output.

Capture a Particular Window/Area:

Type the following command, it will change the mouse pointer to “Cross” symbol. Select the window which you would like to take screenshot or click and drag to take screenshot of particular area.
$ import calc.png

Include the frame using -frame option:

You can also include the “frame” of the window using the -frame option.
$ import -frame Image6.png

Take Screenshot and Resize using -resize option:

You can also take screenshot and resize the screenshot using the -resize option. Pause option is used to make a delay before taking the screenshots.
$ import -window root -resize 640 -pause 4 Pictures/Image7.png
Please refer “man import” for more number of options supported by import command.

4. Use GIMP

You can also take screenshot from gimp. Launch gimp, and click “File->Create->Screenshot”. A new dialog window will open with options similar to gnome-screenshot.


Did we miss any of your favorite tools to capture screenshot? Leave a comment and let us know.

How To Setup Apache Virtual Host Configuration (With Examples)


Using Apache Virtual Host, you can run several websites on the same server.
For example, I can run both "abc.com" and "xyz.com" on a single physical server that has one Apache webserver running on it.


Fig: Apache Virtual Host (Multiple websites, one Apache)

There are two types of Apache virtual host configurations: 1) IP-Based Virtual Host and 2) Name-based Virtual Host. Name-based virtual host is recommended for most scenarios.

IP-Based Virtual Host

In this configuration, when you are pointing two websites (with different ip-address) to the server that runs Apache, that physical server should have two different ip-address configured.
This means that the server should have two ethernet cards, each one of them configured to the ip-address of the corresponding website that Apache virtual host will be serving. So, this is not practical for most aspects, and you should not be using this.
In the following example, the server contains two NIC cards, one is configured with 192.168.101.1 ip-address for "abc.com", another is configured with 192.168.102.1 for "xyz.com". Both these ip-address are served by a single Apache webserver running on that server using IP-Based virtual host.
Fig: Apache IP-Based Virtual Host

Name-Based Virtual Host

In this configuration, 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.
In the following example, the server contains only one NIC card, which is configured with 192.168.101.1 ip-address. The DNS entry for both abc.com and xyz.com website points to 192.168.101.1 ip-address. When Apache recives a request, it looks for the hostname entry in the HTTP header, and serves the corresponding website.

Fig: Apache Name-Based Virtual Host

1. Uncomment httpd-vhosts.conf in httpd.conf

If you’ve installed Apache 2 from source, by default, the following line will be commented in the httpd.conf file. Uncomment this line.
# vi /usr/local/apache2/conf/httpd.conf
Include conf/extra/httpd-vhosts.conf

2. Setup virtual hosts

Modify the httpd-vhosts.conf as shown below to setup named-based virtual host setting for two hosts.
  • 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 abc.com and xyz.com listening on the same port 80. So, there will be two <VirtualHost *:80> </VirtualHost>, one for each website.
  • When you go to abc.com, the files under /usr/local/apache2/docs/abc will be served by Apache; and the access_log and error_log for this site will go under /usr/local/apache2/logs/abc
# vi /usr/local/apache2/conf/extra/httpd-vhosts.conf
NameVirtualHost *:80

<VirtualHost *:80>
    ServerAdmin admin@abc.com
    DocumentRoot "/usr/local/apache2/docs/abc"
    ServerName abc.com
    ServerAlias www.abc.com
    ErrorLog "logs/abc/error_log"
    CustomLog "logs/abc/access_log" common
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin admin@xyz.com
    DocumentRoot "/usr/local/apache2/docs/xyz"
    ServerName xyz.com
    ServerAlias www.xyz.com
    ErrorLog "logs/xyz/error_log"
    CustomLog "logs/xyz/access_log" common
</VirtualHost>

3. Check VirtualHost Configuration Syntax

Verify virtual configuration syntax using “httpd -S” as shown below. When everything is setup properly, it just displays “Syntax OK”.
# /usr/local/apache2/bin/httpd -S
VirtualHost configuration:
Syntax OK
When something is not configured properly, it will display warning message, including “directory does not exit” message as shown below.
# /usr/local/apache2/bin/httpd -S
Warning: DocumentRoot [/usr/local/apache2/docs/xyz] does not exist
Warning: ErrorLog [/usr/local/apache2/logs/abc] does not exist
Syntax OK

4. Restart the Apache and test

# /usr/local/apache2/bin/apachectl restart
Now, when you go to abc.com (or www.abc.com), the apache will serve the files from /usr/local/apache2/docs/abc directory.
When you go to xyz.com (or www.xyz.com), the same apache running on the same server will serve the files from /usr/local/apache2/docs/xyz directory.
Just to reiterate, for the name-based virtual host to work properly, the DNS entry for both these websites should be pointing to the same external ip-address of the physical server where the Apache webserver is running.