What is LAMP?

LAMP stack is open source software bundle which all together helps hosting dynamic website and the web apps. LAMP stands for four essential software packages that is necessary to run dynamic webpages. ‘L’ stands for Linux operating systems on which platform we will be hosting our websites. ‘A’ stands for apache web server the most popular open source webserver. ‘M’ refers to MYSQL database where the data will be stored. And the letter ‘P’ stands for PHP language which we all know is server side scripting language to server our content from server to the browser.

Assuming we have the Ubuntu server 12.04 LTS installed in our machine we are good to go with our LAMP server installation. In the following Guide we will cover how to install LAMP server in Ubuntu operating system.

Following Topics will be covered.

  1. Pre-required Configuration of Ubuntu
  2. Installing and configuring Apache Webserver
  3. Installing and administrating MYSQL
  4. PHP installation and configuration
  5. Testing out the LAMP server

Pre-required Configuration of Ubuntu

Changing IP Address to Static:

Since we will be hosting websites on our lamp server the Ubuntu needs to have static IP address so that it has fixed public facing IP address. Most of the time when we install Ubuntu we leave the basic configuration as it is. By default Ubuntu act as DHCP client and gets its IP address on boot up from the DHCP server which is if it’s in home network from our Router or in enterprise network it gets its IP address from the DHCP server. We don’t want that. We want our LAMP server to have fixed IP address.

In order to do that we will make some changes to the network configuration file of our Ubuntu systems.

We need to make changes to the file /etc/network/interfaces

As root user with following command:

vi /etc/network/interfaces

We add following lines into the file

iface eth0 inet static






Here we made our primary network adapter eth0 from DHCP to static and set it up with static IP address of

In our lab network its in network so the broadcast address will be and the default gateway which is our router address is :

Depending on your network configuration your IP configurations will be different from the above. For more details you can use command line ifconfig in linux or ipconfig in windows to know your IP settings.


Fig: 1 : Changing TO Static IP address

We need to also add our dns server address to the resolv.conf file in the Ubuntu by issuing the following command:

Vi  etc/resolv.conf


Fig-2: Channing the nameserver

We need to restart the eth0 now by issuing following command:

/etc/init.d/networking restart or service network restart

We are assuming we are issuing all the above commands as root users. If not we have to add sudo before each of the commands and type in the root password to execute each commands.

Creating User account:

It’s not good practice to run command or manage our server as root always. So we will create user account in our Ubuntu system.

We create user account admin.

By following command:

sudo adduser PickawebLAMP

Then we type in the password for the admin


Fig-3: Adding User account.

We can give root level privilege to admin so it can do root level work without needing to logging into the root account.

We need to add first open sudouser file by the following command

sudo /usr/sbin/visudo

Under the user privileges add the following line so we give user admin same root level privileges.

Set up Remote SSH for Remote Administration:

We at first install openssh client by following command:

sudo apt-get install openssh-client

Then we install openssh server by the following command:

sudo apt-get install openssh-server

We have to make changes to the ssh configuration file which is located at /etc/ssh/sshd_config file.

We at first open the configuration filer by issuing the following command:

Sudo vi /etc/ssh/sshd_config

We have to make the public authentication from no to yes. If it’s already yes we have to make sure the following line is not commented out.

PubkeyAuthentication yes

Also we can change the openssh client to listen to other port than 22 so that the attacker cannot easily find out the openssh server running.

We can add banner and make openssh to show the banner every time new connection is made.

For showing up the contents we need to make changes to the Banner /etc/issue.net In the /etc/ssh/sshd_config file.

After making all the changes to the ssh configuration file we need to restart ssh server by following command:

sudo service ssh restart

Creating SSH Keys:

SS keys authenticates the two host participating in the SSH connection. We can create the SSH keys by following command:

ssh-keygen -t rsa

Installing and configuring Apache Webserver

In our first step we will be installing the most popular webserver in the world Apache webserver. It’s easy to use and the flexibility it has in its configuration gives users more control and above all it’s completely free.

We will at first install the necessary package for apache in our Ubuntu. We will be downloading the necessary packages from the Ubuntu repository.

At first we log into our Ubuntu systems.

At first we update our Ubuntu systems with the following command

apt-get update

It will create the RSA keys and you will be prompted to key in the password as passphrase for the keys. After typing in the password the RSA keys will be stored locally. The public key is saved in the file ~/.ssh/id_rsa.pub, while is the private key is stored in ~/.ssh/id_rsa.

After updating our system we install apache webserver in Ubuntu by the following command

apt-get install apache2


Fig-4: Installing apache server

After successful installation of the apache2 webserver if we open our Firefox web browser and type in local host which is loopback address we will see apache page showing saying it work as how below in the picture.


Fig-5: Apache server Default page.

Check if the Hostname is set up properly in the Ubuntu.

We need to make sure when we issue hostname command it confronts to the fully qualified domain name.

We have to issue following command in the command line:


hostname –f


Fig-6: Testing the hostname

As we can see from the above picture it shows the fully qualified domain name.

If it does not show up we need to change the hostname file in the etc directory by echoing whatever the hostname we want to put.

In our case we chose lamp. By the following command

echo “lamp” > /etc/hostname

hostname -F /etc/hostname

Configuring Apache:

If we want to start, stop and restart apache manually we have to issue following command

For stopping apache2 server

sudo /etc/init.d/apache2 stop

If we want to restart apache2 again issue following command

sudo /etc/init.d/apache2 restart

or if we simply want to start apche2 we need to type in following command

sudo /etc/init.d/apache2 start

By default apache2 will restart every time our Ubuntu server starts as apache2 service get automatically added to the init.d list.

If we do not want the apache2 to restart as automatically when ubunturestrat we need to remove it from the init.d list by issuing following command

sudo update-rc.d –f apache2 remove

if we want to get the default behavior back to get the apache restarts as the server restarts we can go back to default by typing in following command

sudo update-rc.d apache2 defaults

Note: that we using sudo as remember we made the PickawebLAMP user usdo privilege in visudo file by giving it all user rights.

This way we do not have to change back to root user to carry out root level task.

If we want to check the version of the apache webserver we can type in following command and see the result in the picture

apache2 –v


Fig-7: checking apache server version

Finding Configuration Files:

If we want to get more information about the apache server installed we can type in

apche2ctl –V

This will give you more information about the apache module, architecture of the apache the server configure file where it is located. We can type in apache2ctl –S to find out more information where we can find out the various configuration file like error log file, server root file locations etc.



Fig-8: Finding further apache2 configuration

Setting up Public_html with Virtual hosts in apache server:

By default we know apache shows up what is inside the var/www in the localhost address. Now we can work with it but what if we want to work with multiple sites let’s say for web development work. We can do that by changing our apache public folder to public_html to whatever the website we want to look at.

In the following guide we will create two virtual hosts (pickaweb.lamp1) and (pickaweb.lamp2) on our localhost which is under our PicakwebLAMP user.

The concept of virtual hosts is its way apache can run multiple websites by sharing its resources. The virtual hosts can run on single IP which in our case we will show running it on our localhosts also it can run on per IP based as well.

Let’s get started:

As we have installed apache2 in our localhosts before lets create making virtual directories for our virtual host which is pickaweb.lamp1 and  pickaweb.lamp2

Creating virtual directories and simple index.html pages:

Let’s create directory for pickaweb.lamp1 under var/www directory by issuing following command

sudo mkdir -p /var/www/pickaweb.lamp1 /public_html

sudo mkdir -p /var/www/pickaweb.lamp2 /public_html

We need to give permission to the above directory for our PickawebLAMP user since above directory is under root permisisons.

We can do that by following Ubuntu chown –r command

sudo chown -R $USER:$USER / var/www/ pickaweb.lamp1 /public_html

sudo chown -R $USER:$USER / var/www/ pickaweb.lamp2 /public_html

Here whatever the user logged into the terminal will get ownership access. Also we need to give permission to the /var/www folder for user to have look into it and work with the website we will create by following command

sudo chmod -R 755 /var/www/

Now we have all the permission needed to work with /var/www directory to host our virtual hosts.

Now let’s create simple index.html for our pickaweb.lamp1 and pickaweb.lamp2.

Lets create index.html and open it with our edit vi by issuing following command:

sudo vi /var/www/pickaweb.lamp1/public_html/index.html

It will create index.html inside the public_html directory and it will open in vi editor

We need to type in some simple Html code so that it populates in our apache webserver when we browse for this index.html page.

So we type in as follows:






<h1>Welcome To pickaweblamp1 website</h1>



Save and close the file. We have to do it same for our second pickaweb.lamp2 hosts as well

By issuing same command as before:

sudo vi /var/www/pickaweb.lamp2/public_html/index.html

And we type in the almost the same as before






<h1>Welcome To pickaweblamp2 website</h1>



As you can see from the picture we typed in as follows:


Fig-9: Simple index.html for pickaweb.lamp1


Creating host file for our Virtual hosts:

Apache has its own default host file name 000-default.conf. We need to make something similar to this for our two hosts file pickaweb.lamp1 and picakweb.lamp2

We need to type in two following command one each for our two virtual hosts to have similar vonfiguration file as the default apache configuration file.

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/pickaweb.lamp1.conf

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/pickaweb.lamp2.conf

Now we need to make changes to the configuration file. Let’s do it for our file pcikaweb.lamp1.conf

We open it by typing:

sudo vi /etc/apache2/sites-available/pickaweb.lamp1.conf

If we look into the configuration file we will see it has something like this as default configuration file will be:

<VirtualHost *:80>

# The ServerName directive sets the request scheme, hostname and port that

# the server uses to identify itself. This is used when creating

# redirection URLs. In the context of virtual hosts, the ServerName

# specifies what hostname must appear in the request’s Host: header to

# match this virtual host. For the default virtual host (this file) this

# value is not decisive as it is used as a last resort host regardless.

# However, you must set it for any further virtual host explicitly.

#ServerName www.example.com

ServerAdmin [email protected]

        DocumentRoot /var/www/html

# Available loglevels: trace8, …, trace1, debug, info, notice, warn,

# error, crit, alert, emerg.

# It is also possible to configure the loglevel for particular

# modules, e.g.

#LogLevel info ssl:warn


ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined


We need to make changes to the above bold letter part where it says server name as our pickaweb.lamp1  which will show at the top of the windows in browser bar. And document root need to be changed to var/www/pickaweb.lamp2/public_html/index.html

We can add in Serveralias which can be used instead of pickaweb.almp1 in the browserbar to point to the same host. So we add and make changes top the following lines.

ServerName pickaweb.lamp1

        ServerAlias pickaweb1

        ServerAdmin [email protected]

        DocumentRoot /var/www/pickaweb.lamp1/public_html


We can see it now how our pickaweb.lamp1.conf file look like in the picture below:


Fig-10: Pickaweb.lamp1.conf file

 We need to do same to the Pickaweb.lamp2.conf file as show above with necessary changes.

Now we need to make our configuration file active as our apache still pointing towards the default 000-default.conf

So let’s make our two configuration file active by typing

sudo a2dissite 000-default.conf

sudo a2ensite pickaweb.lamp1.conf

sudo a2ensite pickaweb.lamp2.conf

It will make our two newly made configuration file active but it will prompt our apache server to restart.

So as we learned earlier we restart apache server by issuing:

sudo service apache2 restart

One final thing we have to do before we can test our two website we made. Ubuntu has its hosts file under /etc/hosts where if we get in we will see is pointing toward host name localhost.

That’s why when we type in hostname its actually refereeing to the loopback address.

As we promised earlier we will run our two website under one IP address. Here in this /etc/hosts file we ill point our two pickaweb.lamp1 and pickaweb.lamp2 to

So we edit our /etc/hosts file by typing:

sudo vi /etc/hosts

Then we add pickaweb.lamp1 pickaweb.lamp2

Under localhost

Then we save and exit.


Fig-11: Editing Hosts file

Now if we go to our Firefox browser and type in pickawen.lamp1 and pickaweb.lamp2 we will see it shows

Welcome to pickaweblamp1 and pickaweblamp2 website as shown in the picture below.

test-virtual-host-1 test-virtual-host-2

Fig-12: Testing our Virtual Hosts


We hosted two virtual hosts in our localhosts loopback IP address and this way we can hosts multiple hosts in one IP address in our localhosts or local network to work on our websites when we have multiple websites to work on. If we want this two websites to be accessed from outside network we need to actually edit our DNS server with valid DNS record with real domain name and the address.


Tweaking our apche2 server and securing it:

Now that we have our apache server up and running lets optimize it and learn about some basic configuration and secure our server.

All the configuration file of our apache2 server is under /ect/apache2 directory

We have main apache2.conf file where make changes to directories permission, keep alive, timeout, maximum keep alive request etc.

Then we have ports.conf file where we can make changes to the port based security to allow and refuse connection to our server.

mods-enabled/, conf-enabled/ and sites-enabled/ are used for module configuration, global configuration management and the virtual host configurations.

So let’s tweak our webserver.

Lets show you how to work with modules. Modules are extra add-on power to the server which we have some of them built in when we installed apache before.

We can find all the available modules under /etc/apache2/mods-available

As we can see we have lots of modules available in our apache server in the following picture


Fig-13: Modules available

We can check all the loaded module by issuing apache2ctl –M command.


Fig-14: Loaded Modules

Loading-Downloading-Editing Apache server modules:

Any module that is available inside the mods-available directory but not enable by the apache2 by default van be enable by the following command:

sudo a2enmod rewrite

Though mod_rewrite configuration file is not present in the mods-available directory. It can be configured inside the .htaccess configuration file or inside the apache2.conf file.

Here we have shown it with the rewrite module. This modules helps to create unique URLS based on the contents requested on apache server.

After enabling new modules we need to reload our apache server.

sudo service apache2 reload

One of the great module which is built in is the status module. This module shows us all the requests and the current load of our server. We can edit this file by editing the status.conf file by typing the command:


vi etc/apache2/mods-available/status.conf

We can make changes here like where from we want to get the connection from. This settings can be edited under server status directory.

The normal configuration are such:

<Location /server-status>

SetHandler server-status

Order deny,allow

Deny from all

Allow from ::1

Allow from none


We can put our IP address from where which we want to access our server. Or we can simply put the local network mask like to accept all the incoming connection from our local network.

Note: While putting the IP address allow don’t put the IP address of your server in our case the address We need to give the IP address of the Machines we want connection from.

After editing any module configuration file we need reload our apache2

service apache2 reload

Now we can see the status of our apache2 server by typing in the lcoalhost/server-status in the Firefox or any browser URL bar.

We will be presented with server status updates like its load time, cpu usages etc as you can see from following picture.


Fig-15: Apache Server Status

How to install NEW MODULE in apache:

We will see now how to add new module into the apache mods-available directory and enable and load it.

We will use PageSpeed module. This module optimizes apache and its contents by compressing it, adding caching facilities. It also can resize files and truncate unnecessary spaces in configuration file by removing any whitespaces.

So we will install PageSpeed module in our apache. Since we have 64 bit Ubuntu we need to type in following command to download mod-pagespeed module 64 bit debian packages for our server.

wget https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-stable_current_amd64.deb

we need to depackage the debian file by following command

sudo dpkg -i mod-pagespeed-*.deb

Then we have to install it by typing

sudo apt-get -f install

We need to restart our apache server to make this module active. So we type in:

sudo service apache2 reload

Now the Mode-PageSpeed module will start working. If we want to further configure its configuration file which is located at etc/apache2/mods-available/pagespeed.conf.

By default PageSpeed module comes with decent default configuration which should be good but for different website the settings can be different and we can configure whatever the way we like.

We can do some basic tweaking of PageSpeed module as follows:

Let’s first open the PageSpeed configuration file with our favorite VI editor for editing by typing in:

vi /etc/apache2/mods-available/pagespeed.conf

First setting we see is the ModPagespeed on or off option.

We can set it to on or off according to our wish.

ModPagespeed on

Or ModPagespeed off

We can set the virtual host here to get the global configuration or to have its own configuration by setting

ModPagespeedInheritVHostConfig on or off

Another powerful features in PageSpeed module is the Rewrite levels. It has three basic levels.

One default and safe for most of the website is the corefileters. Which is set by commenting out the following line as:

ModPagespeedRewriteLevel CoreFilters

If someone wants to have its own filters then this default core fileters needs to be disable by issuing passthrough

ModPagespeedRewriteLevel PassThrough


Default set of corefilters have lot of filters to name few such are
















Disabling any one of above requires issuing following command

ModPagespeedDisableFilters rewrite_images

This will use all the above filters except the rewrite_images filters

You can allow which hosts can look into the pagespeed statistic in the location/pagespeed_admin directory in the configuration file. In our case only lcoalhosts are allowed to look into the pagespeed statistics. If we want we can add in other hosts to allow looking into the statistics.


Fig-16: Pagespeed_admin settings.

We can also use pagespeed_module to specify which URL matchin not to be rewritten. By default pagespeed rewrites all the css images, javascript within html file unless we instruct apache not to rewrite it.

In apache we can allow or disallow by the following command:

ModPagespeedAllow wildcard_spec

ModPagespeedDisallow wildcard_spec


In that wildcard we can instruct like

ModPagespeedAllow http://*pickaweblamp1.com/*/styles/*.css

This will look for any patter matching above wildcard and will try to rewrite it.

After any configuration to the module is done we need to issue server restart by the following command to take any changes into effect.

service apache2 restart

Making apache listen other than port 80

By default apache listen to port 80 but if we want we can change it to other port than 80 to whatever we like.

For this to happen we need to change to the main apache2 port configuration file which is located at /etc/apache2/ports.conf

We open it for editing by issuing following commands:

vi /etc/apache2/ports.conf

Then we have to type in whatever the port we want our apache2 to listen to. Let’s say we want it to listen to port 2031 we can do that so by specifying port number after listen

Listen 2031

What if we want to listen to both port 80 and 2031 we can do that by adding one line after another as follows:

Listen 80

Listen 8010

We also can specify specific IP address to accept connections. For that we need to use IP address of the hosts we want connection from and also we can specify the port associated with it as follows



Here we specified IP address to accept connection on port 80 and to accept connection on port 2031.

Also we need to add in the virtual hosts that will use the port we configured.

Let’s say our pickaweb.lamp1 will use port 2031

So we type in

pickaweb.lamp1 *:2031 in the ports.conf file

Now we made changes to the port.conf file we need to make changes to the 000-deafult.conf file to make it work.

So we go to edit /etc/apache2/sites-enabled/000-default.conf by

vi /etc/apache2/sites-enabled/000-default.conf

We need to change to the first line where it previously was <VirtualHost *: 80> and if we want it to listen to 2031 we change it to <VirtualHost *: 2031>

Then we have to restart apache2 server by typing sudo service apache2 restart

Now assuming we had configured two virtual hosts we need to make changes to the virtual hosts configure file in our case pickaweb.lamp1.conf and pickaweb.lamp2.conf file.

If we open the pickaweb.lamp1.conf file by typing

sudo vi /etc/apache2/sites available/pickaweb.lamp1.conf

We will have to configure The bold part of the VirtualHost :80 as seen below

<VirtualHost *:80>

ServerName pickaweb.lamp1

ServerAlias pickaweb1

ServerAdmin [email protected]

DocumentRoot /var/www/pickaweb.lamp1/public_html

ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined

#Include conf-available/serve-cgi-bin.conf


To whatever the port we want to change to. As we configured earlier pickaweb.lamp1 to use 2031 port so we change it to

<VirtualHost *:2031>

ServerName pickaweb.lamp1

ServerAlias pickaweb1

ServerAdmin [email protected]

DocumentRoot /var/www/pickaweb.lamp1/public_html

ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined

#Include conf-available/serve-cgi-bin.conf


This way if we want our pickaweb.lamp1 virtual host to listen to multiple ports we need add in

Then we restart the server as always sudo service apache2 restart

If we now do the pickaweb.lamp1:2031 and if it load up correctly then it’s working.


Setting FollowSymLinks and SymLinksIfOwnerMatch:

In apache webserver configuration file there is options set under directory as


<Directory />

 Options SymLinksIfOwnerMatch


As above the SymLinksIfOwnerMatch the apache server follows the symbolic links in the directory as well as it at first verifies the ownerships of the link for which the apache has to use additional resources. It will only follow the symbolic link only if the requested directory or link is owned by the user requesting it.

There is other option FollowSymLinks if set the server only checks the symbolic links in the directory.

In our pickaweb.lamp1.conf file if we have look the bold part

<VirtualHost *:80>

ServerName pickaweb.lamp1

ServerAlias pickaweb1

ServerAdmin [email protected]

DocumentRoot /var/www/pickaweb.lamp1/public_html

        <Directory />

                Options FollowSymLinks Indexes

                AllowOverride None



ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined



We set option Options FollowSymLinks Indexes. It will make apache only to follow symbolic link in this directory without verifying the ownership of the user. Thus it put less pressure on apache server for processing. And make apache server run bit faster.

So it’s better to use FollowSymLinks everywhere and only use SymLinksIfOwnerMatch in a directory where the ownership checking is required.


Optimizing: Maximum Concurrent Connection:

Setting the maximum client in the /etc/apache2/apache2.conf file sets the maximum requests the apache server will handle at a time. Its good idea to find good value for this options as keeping it too low will make apache server refusing many connection while keeping it higher will use up the resources unnecessarily.

The way one can find out the correct maxclients connection number is by determining the RAM a server has and dividing it by the size of the child process.

If the webserver has too many requests than it can handle and usually eats up the RAM it has the server comes to stall and it crashes. So we want to give load to our server less than it can handle with its physical memory.

For this we can keep eye on our apache server by following command

watch -n 1 “echo -n ‘Apache Processes: ‘ && ps -C apache2 –no-headers | wc -l && free -m”

It has output like as below where it shows the amount of memory used and free memory as well as the cached, and shared memory information. It also shows the amount of swap memory it has.


Fig-17: Watching server’s Memory status


Setting Correct KeepAlive & KeepAlive Timeout Time:

If we check our apache2.conf file in the image below we see KeepAlive is set to on and KeepAlive timeout is set to 5 which is default configuration.


Fig-18: KeepAlive & KeepAlive Timeout Value

The keepAlive makes it possible to send several requests over one TCP connection which is useful in a situation where a particular website has lot of dynamic contents and loading those contents require many concurrent requests which if KeepAlive is set to on can be sent over one TCP connection. If KeepAlive is set to off for each request the apache will create new TCP connection which creates more bottleneck on the server.

Also Keep Alive Timeout instructs apache how long it will wait for next requests from particular connection if sit idle. In our case it is set to 5 second. The better choice is to keep it in between 2 to 5 seconds. But it should not be made too high as it will keep child process stuck with requests for long time and in process denying other legitimate requests.

Compressing HTTP and Caching:

In HTTP/1.1 HTTP compression is standard. The way it works is any requests sent to the server by the client it uses GZIP or deflate encoding to create that response payload then send it to the client. The client then unzip the payload. In the client side there is no need to install nay extra software to unzip it as all the modern browser does that automatically for the client. Compression is useful as it saves the bandwidth and it can compress up to 75% at times. In apache the module that helps compression is the mod_deflate module.

Mod_deflate module is by default installed in our apache server. But we need to enable it by typing:

a2enmod deflate

Then we restart our apache as always /etc/init.d/apache2 restart or by service apache2 restart

Now we can configure deflate two ways.  We can explicitly mention the file we want to include or don’t want to include in the MIME type. We also can enable mod_deflate for whole apache2 server or just for our each of the virtual hosts we created earlier. We can configure in the golabr apache2 configuration file for our deflate or we can do it per virtual host wise.

Let’s say we want to compress only compress HTML, text and CML file we can do so by adding


AddOutputFilterByType DEFLATE text/html text/plain text/xml

As you can see from our configuration below:


Fig-19: Mod_deflate configuration

If we want to compress all the types but keeping asides some of the few we can do so by adding following line:


SetOutputFilter DEFLATE

SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ \

    no-gzip dont-vary

SetEnvIfNoCase Request_URI \

    \.(?:exe|t?gz|zip|bz2|sit|rar)$ \

    no-gzip dont-vary

SetEnvIfNoCase Request_URI \.pdf$ no-gzip dont-vary


Here we are saying compress everything except gif,jpeg and png file as well as we are saying do not compress pdf and file already compressed like tar.gz and zip file which make sense.


We also can add following line for supporting compression by the browsers especially old browser to compress our data.

BrowserMatch ^Mozilla/4 gzip-only-text/html

BrowserMatch ^Mozilla/4\.0[678] no-gzip

BrowserMatch \bMSIE !no-gzip !gzip-only-text/html


This tell browser to compress data for other file including html as previously browser used to support only compressing HTML document.

Some of the file that we think need to be compressed are as follows:












And the files we do not think need to be compressed anymore are:

  • images – gif, jpg, png
  • archives – exe, gz, zip, sit, rar

Pretty obvious right!!!

Now we have to restart the apache server as always service apache2 restart

Setting the MaxRequestsPerChild:

The maxrequestsper child instructs the apache server as to how many requests an individual child process will handle. Whatever number we put here the child process will serve that many requests and after that it stops. But if we set it to 0 it will keep accepting the requests and it will never expire. It is better to keep it in 1-3 thousands.

MPM module in apache:

MPM refers to Multi-processing method. By the help of MPM apache can handle multiple conenctions .Worker and the prefork are the two main type of MPM in apache. The way worker operates is it creates extra threads on top of child process to handle each new connections where the prefork MPM creates new process for each new connections. One can easily switch between these two and find out which sooth them best.

One of the easiest way to find out which MPM one server is running is by issuing

aptitude search apache2-mpm-

As we can see in the following picture our server we have four MPM available for our server as indicated by the letter P preceding it. If it was installed it would have I letter preceding it.


Fig-20: Available MPM in apache


Another way one can find out is by issuing apache2ctl -l g which will show compiled modules within apache server. In our case it will now show any MPM as we have not installed any yet.

We can install it by issuing

apt-get install apache2-mpm-worker

apt-get install apache2-mpm-prefork

As we can see now these two MPM is been installed as shown in the picture below


Fig-21: Installed MPM in apache

We now have to enable any of the MPM we want in our case lets enable MPM-prefork.

The way we do it as we learned earlier any module we enable it with

a2enmod mpm_prefork

Then we have restart the apache server by service apache2 restart

Now if we want to see available moulde for MPM in our server we type in

ls /etc/apache2/mods-available/mpm* and we see we have three MPM event, worker, and prefrok available







Now if we want to find out the active MPM module we type in:

ls-l /etc/apache2/mods-enabled/mpm* and we see our preform module is been active

rwxrwxrwx 1 root root 34 Jun 25 10:19 /etc/apache2/mods-enabled/mpm_prefork.conf -> ../mods-available/mpm_prefork.conf

lrwxrwxrwx 1 root root 34 Jun 25 10:19 /etc/apache2/mods-enabled/mpm_prefork.load -> ../mods-available/mpm_prefork.load

We can see below the available and active MPM module shown in the picture:


Fig-21:  Active and available MPM module


Configuring MPM:

The MPM module settings for each module like worker, event, prefork   etc is configured in its own ifmodule directives. For example setting for prefork module we can declare in

<IfModule mpm_prefork_module>

Similarly for worker module we have to declare in <IfModule mpm_worker_module>

So let’s dive in prefork module.

If we want to configure the prefork module we need to edit the mpm_prefork.conf file located /etc/apache2/mods-enabled/mpm_prefork.conf

So we edit the prefork configuration file by


We the default configuration is such as follows:

<IfModule mpm_prefork_module>

StartServers                     5

MinSpareServers           5

MaxSpareServers          10

MaxRequestWorkers         150

MaxConnectionsPerChild   0



The Startservers indicates how many child process the server will initiate when it starts. Here we set it to 5. If we are expecting heavy traffic we have to increase the number here.

MinSpareServers   indicates minimum how many child server process is in back up

MaxSpareServers indicates maximum how many child server process will be reserved in backed up.

We kept    MaxConnectionsPerChild to 0 means we do not want out child process to get expired while dealing with requests.

As we can see from the images below the prefork module configuration file look like this:


Fig-22-: Prefork Module configuration file.


Reducing DNS lookup:

The hostname in the lookup directives makes it possible to log in as hostname rather than IP address. Every time hostname needs to be matched to IP address the apache server has to go for DNS lookup which creates extra overhead. It’s recommended to keep the DNS lookup off. By default DNS look up is disabled. Even when we want to use allow and deny we should use IP address instead of hostname which will stop apache to go for DNS lookup and use up extra processes.


Configuring Content Negotiation:

Content negotiation is the way apache server can delivers the content to the browser the way it likes. We can configure it by the mod_negotiation module which comes inbuilt with the apache2 server.

Two ways one can configure the content negotiation. One in Type maps and one place in Multiviews.


To configure TypeMaps in a directory where we want content negotiations we need to create .htaccess file and include the following line

AddHandler type-map var

In the var extension we can use index.html.var which is apache by default.  We ca explicitly link with the

Variant like index.html.var or we can link to the more default index type by declaring all in the directory Index.

DirectoryIndex index.html.var index.html index.php


In Multiviews one can enable it inside the .htaccess file by adding following line to whichever the directory we want multiviews to be enabled:

Options +MultiViews

We can set MultiViews for content type like serving Xhtml for the user agent who support it if not it serves html pages.

We have to add associated file types with apache at first:

AddType text/html;charset=UTF-8 .html

 AddType application/xhtml+xml;charset=UTF-8;qs=0.999 .xhtml # low quality so that old browsers will get .html

Above configuration instructs apache to interpret the file according to its extensions. Like if browser wants to get index page from apache if the browser supports xhtml it will serve the index.xhtml page if not it will serve the index.html page.

We can set up preferred language with MultiViews so that it can negotiate automatically with the browser.

We have to set up the extensions like before as follows:

AddLanguage en .en       # English

 AddLanguage de .de# German Language

So if name out file like index.en.html and index.de.html. Whatever the user agent’s default language the relevant file will be served by the apache.

It’s better to use type maps as MultiViews force apache to look into the directories which creates overhead for the apache server.


Isolating Apache Server workload for static and Dynamic Content:

Apache server if working with dynamic pages can take significant amount of memory and it keep using up the memory until it fully loads the dynamic contents. It is true even for a page with only images as it treats it like dynamic page and in process allocate lots of memory for work that it does not need that much of memory. This significantly reduces the apache performances. If we can set up apache server to separate its job to serve static and dynamic pages with less memory process for handling static pages and high memory process for handling dynamic pages our server will then better handle its Memory.

We can achieve this by redirecting static page requests to lightweight front server and more intense dynamic pages to back end heavy server. We can achieve this by Mod_proxy modules and rewrite module.

For example we can set up lightweight apache server on one port 80 and heavyweight server on other port 5500 so that we can redirect static pages and dynamic pages accordingly.

Then our configuration file will be:

ProxyPassReverse / http://%{HTTP_HOST}:5500/

 RewriteEngine on                                            

 RewriteCond   %{REQUEST_URI} !.*\.(gif|png|jpg)$

 RewriteRule ^/(.*) http://%{HTTP_HOST}:8088/$1 [P]


Here we are instructing apache that all the requests to be sent to the backend server listening on port 5500 except the images.  Then when the backend server response it first goes to the front end server and then to the client.

This way we can isolate dynamic and static page requests as well as we can build on this configuration and make the heavy request to be forwarded to the external server as well.


Unload Unnecessary Modules:

Apache server works by setting module wise. Administrator can choose set of modules he wants in his server and enable it, tweak it the way he wants. Modules are compiles statically and dynamically. Statically compiled module use less RAM but downside being adding and dropping the module needs recompiling into apache where else dynamically loaded modules does not need compiling as it can be loaded by LoadModule command .

Loading unnecessary module adds extra load to the apache resources so unloading unnecessary modules can improve the performances of the apace server.



Allowoverride option in default /etc/apache2/apche2.conf in directory is normally set to none. If set to none the apache server looks for .htaccess file in each directory it traverse. For example configuration such as follows:

<Directory /var/www/>

        Options Indexes FollowSymLinks

        AllowOverride None

        Require all granted

</Directory>Makes apache webserver to look for all the .htaccess file in each subsequent directories like /var , /var/www , /var/www/html if one request like /index.html is made. This additional lookup slows down the apache server.

So it’s recommended to make changes to as follows:

<Directory /var/www/>

        Options Indexes FollowSymLinks

        AllowOverride ALL

        Require all granted

</Directory>So that apache does not have to look for .htaccess file in each directory. If there is need for .htaccess file in any directory make it enable for that particular directory only.

We have to restart apache now to make the .htaccess file active.





How to make user friendly URL in apache:

Lot of the time administrator wants to make URL of website more user friendly. For example lets look at following URL of website:



If we want user not to remember the trailing part of the URL we can make it possible in apache with Mod_rewrite module to something simpler like below:


First of all we need to enable rewrite in apache by issuing following command

sudo a2enmod rewrite

Then we restart apache server.

Once the rewrite module is activated we need to open or create .htaccess file in the directory we need to apply rewrite module. This will be valid for the directory the .htaccess file resides as well as the subsequesnt directories as well.

With .htaccess file we can make changes per directory level without needing to configure the main server configuration file.

We then create .htaccess file to the directory we want with following command

sudo nano /var/www/pickaweb.lamp1/.htaccess

Now we want to make changes to the sites for which we are applying rewrite module to. So in the site available directory we make changes to the default 000-default.conf file if we want whole site wise configuration or if we want per virtual host wise configuration we can change to the virtual host configuration file inside the site-available directory in our case pickaweb.lamp1.conf or pickaweb.lamp2.conf file.

We have to make the AllowOverride All in the directory section of either the pickaweb.lamp1.conf or pickaweb.lamp2.conf to enable the .htaccess file for pickaweb.lamp1 or pickaweb.lamp2.conf.

If we want whole site to be available for this rewrite module we need to make changes to the 000-default.conf file.

Now restart the apache server to take its effect.

So let’s say we want http://www.pickaweblamp1.com/index.php?id=712

URL to look like more user friendly http://www.pickaweblamp1.com/712.html


We need to add following rule in the .htaccess file that we made earlier inside /etc/var/www/pickaweb.lamp1 directory Options +FollowSymLinks


RewriteEngine On

RewriteRule ^id/([a-zA-Z0-9]+)/$ index.php?id=$1

Here the

the [a-zA-Z0-9] takes any uppercase of lowercase alpha numeric letters.

  • The asterisk inside the brackets is used to match occurences.
  • ([a-zA-Z0-9]+) it will take all the alpha alphanumeric of 1 character
  • The caret ^ means “start with”, meaning the URL starts with the word “id”.
  • The dollar sign $ means the URL will finish with slash sign
  • The $1 means it will carry whatever was written in the group of brackets before

Now we save the .htaccess file and restart the apache server.

So now clients do not have to memorize the URL as http://www.pickaweblamp1.com/index.php?id=712

When the client type in URL as http://www.pickaweblamp1.com/712.html it will request above URL in the backend by the apache.

More reference on Rewrite is available at: http://httpd.apache.org/docs/current/mod/mod_rewrite.html

This are the steps we can take to optimize our apache server and make it faster and User friendly for the users.

Using ufw for our apache server:

We can certainly made our apache server more secure by like using IPtables or for easier user-friendly UFW or uncomplicated firewall

We can explicatively set rules for IP address and ports for our server

Say we want to allow only 80, 22 and 443 access to our server we can do that by typing:

apt-get install ufw

ufw allow 80/tcp

ufw allow 443/tcp

ufw allow 22/tcp

ufw enable

Installing MSQL and configuring it into our LAMP server:

Now that we have set up the Apache server which is the first functionality of LAMP server lets install the database support for our apache server. We configure open source most popular relational database management system MySQL and delve deep into the configuration of MySQL configuration support for our apache server.

MySQL will provide support for database systems for our apache webserver whenever our websites needs to store data in apache server.

Installing MySQL:

At first we update our server. And then we install the MySQL server and MySQL client by the following command:

sudo apt-get update

sudo apt-get install mysql-server mysql-client

Note: We are installing as root user as previously we have installed apache. We also created Picakweblamp user with sudo privileges. So in order to install with user account we are using sudo in the beginning. If we have root access we do not have to use sudo.

While installing it will ask for the Root user password for the MySQL as follows.


Fig-23: Setting MySQL root password.

We put the password for root user. It’s recommended to put strong password at least 8 characters long with alphanumeric numbers. If we miss to create root password in this stage we can set it later on which we will show you how.

Now let’s run the MySQL we installed by following command:

sudo service mysql start

It will say MySQL already running which is good news for us. At the time of the MySQL installation it starts the service. If it does not the above command will start it.

By default the MySQL should run at the boot time. Just to make sure it runs at the server boot up lets issue following command:

sudo /usr/sbin/update-rc.d mysql defaults

MySQL shell:

We can manage MySQL in various ways but one of the basic ways is to getting into the MySQL shell environment from where which we will set the root passwords, create users, create new database, Give permission to users etc.

To get into the MySQL shell as root user we issue

mysql -u root –p

Or from normal user we issue

/usr/bin/mysql -u root -p

We will be prompted for the root password that we set up earlier if not it will ask for the root password to set. This is where we can set the root password if we have missed in the earlier time during the MySQL installation.

After successful typing in of the root password we will be given a MySQL shell environment mysql> to interact with our MySQL server.

Changing the Root Password:

There might arise need to change the root password that we set up earlier which can be for reason like setting weak password or forgetting the root password or setting no password means blank password for the root user of MySQL.

We can certainly do that by following command typing into the MySQL shell environment.

UPDATE mysql.user SET Password = PASSWORD(‘password’) WHERE User = ‘root’;

Here if we are familiar with SQL language we will know it’s more like SQL statement as it ends with semicolon where it is setting new password whatever will be given inside the ‘password’ filed will be set as new password for the user root.

Now to make this changes to take effect we need to flush previously stored root password.

We can do that by typing:


Finding the user account information from MySQL server:

MySQL stores its own database information in database named mysql. It its database there is user field, host field, password field by querying which we can find out about the user account, and its password (In encrypted format), the hostname associated with it.

To see the users, hostname, password filed information from the MySQL server we need query it with the following command:

SELECT User, Host, Password FROM mysql.user;

As we can see from the following picture we have only root user and system user in our MySQL server:


Fig-24: MySQL user account information

Note: The semicolon we using in MySQL shell for interacting with our MySQL server is used to indicate the end of the MySQL statement. If we do not use semicolon after one statement it will expect more input from us. So to denote the end of one statement we need to end it with semicolon or if we want to run two line of statement we need to separate it with -> sign and end with semicolon.

Creating New Database:

Right now we only have mysql database where MySQL stores its user account information as we have seen previously.

Let’s create new database name pickaweb. We can do that by typing as follows:


You can put whatever you want your database name to be in place after DATABASE.

The above command will create pickaweb database.

We can get confirmation of the new database lists in our MySQL server by typing:


We see below we have pickaweb database in our MySQL server.


Fig-25: Current list of database in MySQL server.


Creating Non-root user account for MySQL server and Permitting permissions:

Running MySQL server with root account privileges is not recommended. Root user has the ability to delete, add, modify users and records so it’s better to create other non-root user account to manage MySQL server. Let’s create user account name pickaweb in our MySQL server.

To create piackaweb user in our MySQL server with password pickaweblamp1 we type in following account

INSERT INTO mysql.user (User,Host,Password) VALUES(‘pickaweb’,’localhost’,PASSWORD(‘pickaweblamp1’));

Now to make this changes to take effect we need to flush previously stored root password.

We can do that by typing:


Now to check whether our user pickaweb is been created. We can confirm that by issuing following command to find out about the user account information:

SELECT User, Host, Password FROM mysql.user;

We see we have pickaweb account tied with our localhost as follows:


Fig-26: pickaweb user account creation in MySQL

Now that we have created pickaweb user it does not do anything. In order to make this user useful we need to give permission to this user on to any databases we want which is available in our server. We don’t we give pickaweb user give permission to the new database we create earlier named pickaweb to have full control over it.

We can do that by typing following command:

GRANT ALL PRIVILEGES ON pickaweb.*  to [email protected];

We need to issue in the FLUSH PRIVILEGES; to take the above command into effect.

Here we are telling MySQL server to give all the permission on pickaweb database for the pickaweb user account.

Configuring MySQL:

Now that we have covered the basic part of manipulating with MySQL done we can now get into the configuration of the MySQL now. We have to get out of the previous MySQL shell by typing ctrl+c.

First of all we need to find where our MySQL configuration file is located in our server.

Usually MySQL configuration file is located in /etc/mysql. We can cd into this directory and list all the files inside this directory with ls command.

We can also request MySQL for finding where is the configuration file by typing:

/usr/sbin/mysqld –help –verbose

We will see the output as follows where the configuration file will be shown where it is located.

Usage: /usr/sbin/mysqld [OPTIONS]

Default options are read from the following files in the given order:

/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf

Now let’s look further into this configuration file and learn how to make changes to it.

Editing the my.conf file:

My.conf is where the Mysql database server mysqld and client mysql look for its configuration as to how it will work.

My.conf is located at /etc/mysql/my.cnf

We can have look at this my.conf file by opening it for editing by VI editor.

sudo vi /etc/mysql/my.cnf

We will find configuration related to MySQL server (mysqld) is under [mysqld]” and MySQL client (mysql) under [client].

Here you will find mysql client configuration such as port it is listening to, the socket path and also configurations for mysqld like port, socket, PID, base/data/tmp dir. The configuration here will be applied to all the mysql clients in the server. We can fine tune MySQL server settings as well. In the my.conf file under fine tune configuration and query cache configuration following default settings can be tweaked according to one’s need.

ey_buffer              = 16M

max_allowed_packet      = 16M

thread_stack            = 192K

thread_cache_size       = 8

query_cache_limit       = 1M

query_cache_size        = 16M

Network settings are under mysqld and mysql client port and bind address.

The port for both to MySQL server (mysqld) is under [mysqld]” and MySQL client (mysql) should be same here as 3306 by default, we can make changes to the client and server port in the following bold line:


port = 3306


port = 3306


The bind address define from which address the MySQL server is accessible. By default its set to localhost which is our loopback address which prevents other machines to get connection in our MySQL server.

This is valid when we install MySQL server and the application accessing it in our case apache and PHP in same machine. But if the MySQL server is hosted in other machines then we need to bind it to the public facing IP address of that machine so that it can be accessible via internet.

We can make changes to bind address in the following bold line:


bind-address =

 MySQL server has two instances named ‘’mysqld” and “mysqld_safe’’. Usually MySQL run as mysqld_safe underwhich mysqld process gets run. mysqld_safe is starts MySQL with safety features to save MySQL server in the event of crash. Both has same configuration as both uses same configuration under mysqld directory in my.conf file.

 Locating log file:

MySQL log file can be found under /var/log/mysql directory.

We will see there is error.log file inside this directory into which MySQL stored useful logging information which can be worth looking into whenever MySQL gives error.

If for some reason the log file is not there in the above mentioned directory one can easily define the path of the log file in my.conf file at log_error file.

In order to set the above directory as log_error file location add the line after log_error as follows:

log_error = /var/log/mysql/error.log

We need to make sure the directory we chose for the log_error path is user writable. Now restart the MySQL server to take the above changes into effect.

Choosing MySQL database Engine:

MySQL has two database engine “MyISAM” and “InnoDB. The MyISAM engine being the choice by default in PHP version 5.1 and earlier where the InnoDB is being the current choice.

The differences between these two engines for regular user like web developers is not clearly visible as the main difference between these two engines being the fault tolerance and recovery options being robust in InnoDB. MyISAM has better compatibility with applications where as InnoDB is being more robust in handling crashes. So choosing which database engine to use is best left to the apache itself as working with InnoDB needs more configuration than MySIAM.

One can find out the engine used by certain database in MySQL by issuing following command by getting into the MySQL shell command:


Will show it is using MySIAM engine as follows:


Fig-27: Database Engine

MySQL Backup and Recovery:

The most important feature for any database system is its ability to back up the data and recovering it when needed. MySQL can be backed up via command line with help of mysqldump or by phpMyAdmin which we will show it later on when we install PHP support in our LAMP server.

We will at first show you how to back up our mysql database which stored our user information and restore it into our pickaweb database using mysqldump.

Mysqldump is very versatile and popular command line backup tool which can backup and restore multiple databases same time and restore it to remote server.

Backing up a database by mysqldump has following general syntax:

mysqldump -u root -p[root_password] [database_name] > backupfilename.sql

Let’s say we want to back up our mysql database as myswql_backup. In order to do this we need to type in the following statement

mysqldump -u root –plamp1234  mysql > pickaweb.sql;

This will dump the mysql database we had in our server by default into pickaweb.sql backup file.

Now let’s restore the backup file to our pickaweb database we created earlier which was empty.

The way we can do it is by issuing following command in the Ubuntu server shell prompt.

mysql -u root -p  pickaweb < pickaweb.sql;

It will ask for our root password of the MySQL server. Here we used the normal SQL command to restore the pickaweb.sql database into our pickaweb database.

Now let’s see what is inside our pickaweb database now.

Let’s load the database picakweb by getting into our MySQL shell environment at first by issuing

mysql -u root –p

We give root password and we get into the shell environment.

Now as shown earlier we see list of database in our MySQL server by typing

show databases; command

We see we have following databases in our mysql server

mysql> show databases;

| Database           |


| information_schema |

| mysql              |

| performance_schema |

| pickaweb           |


4 rows in set (0.00 sec)

Now we load the pickaweb database by typing

mysql> use pickaweb; command

Now that we have load the picakweb database let’s see how many tables there inside the picakweb database by typing show tables; command

We see we have 24 tables inside the pickaweb

mysql> show tables ;


| Tables_in_pickaweb        |


| columns_priv              |

| db                        |

| event                     |

| func                      |

| general_log               |

| help_category             |

| help_keyword              |

| help_relation             |

| help_topic                |

| host                      |

| ndb_binlog_index          |

| plugin                    |

| proc                      |

| procs_priv                |

| proxies_priv              |

| servers                   |

| slow_log                  |

| tables_priv               |

| time_zone                 |

| time_zone_leap_second     |

| time_zone_name            |

| time_zone_transition      |

| time_zone_transition_type |

| user                      |


24 rows in set (0.00 sec)

Now we need to see the user data which should be user account information same as we seen inside the mysql database user table.

So inorder to see the user table both in mysql and picakweb database we issue in following both commands to verify both have same user table data

SELECT User, Host, Password FROM mysql.user;

SELECT User, Host, Password FROM pickaweb.user;

As we can see from the following picture both have same opy of the data which we made it possible by backing up the mysql database with MysqlDump and then restoring it to the pickaweb database.


Fig-28: Pickaweb and mysql user data table


Backing up More than one databases with Mysqldump:

We can back up more than one databases with one command in mysqldump. As we have picakweb and mysql databases. We can backup both of this to new backup file named pickasql.sql by following command

mysqldump -u root –p –databases mysql pickaweb > pickasql.sql

Now pickasql.sql will have the copy of the two data base pickaweb and the mysql

Backing up All the Databases:

We can back up all the databases of the mysql by following commands:

mysqldump -u root -ptmppassword –all-databases > /tmp/alldatabase.sql

This will back up all the data of our server inside tmp directory as alldatabase.sql

Backing up single table of a database:

We can backup table inside databases individual wise or more than one table. Like below if we want to back up single host table only from pickaweb we can do that by typing following:


mysqldump -u root –plamp1234 pickaweb host > pickawebhost.sql

But if we want to back up more than one table we can do that also by following command:

mysqldump -u root –plamp1234 pickaweb host user proc > pickawebhproc.sql

This will back up host, user,proc table from picakweb database to pickawebhproc.sql

Backing Up database to Remote Host:

We have been backing up to local database till now. If we want we can back up to remote host as well.

Let’s look at the following command:

mysqldump –h -u root –plamp1234 pickaweb host user proc > pickawebhproc.sql

This will back up host, user,proc table from picakweb database to pickawebhproc.sql into remote server

We need to make sure the database port is opened in that remote server before sending the backup file.

We can validate the remote server by issuing following command:

mysql -h -u root -p

If it shows following error

ERROR 1130: Host is not allowed to connect to this MySQL server

Then we have database client connection error.

We can also validate this error by trying to connect to mysql port of the remote machine as follows:

$ telnet 3306

host is not allowed to connect to this mysql server

So in our MySQL server if we want MySQL client running in to get connection from we need to allow this IP address in the MySQL prompt of our server.

So we need to type in following:

$ mysql -u root -p

mysql> GRANT ALL ON *.* to [email protected] ‘IDENTIFIED BY ‘your-root-password’;


We need to also open the port 3306 in the remote host

So now if we try to connect with our remote host it will work fine now.

Database File Compression:

Some times for big file the backup file can be very big depending on the data in the database as well as how many database it is backing up.

So what we can do is compressing the backup file by gzip. The way we can do it is using the same command we used before just before sending the backed up data to a .sql file we need to pipe it through the gzip so it can compress it.

mysqldump -u root –plamp1234 pickaweb host user proc | gzip -9 > [pickawebhproc.sql.gz]

Now we can unzip the aboze .gz file by gunzip with the following command:

gunzip [pickawebhproc.sql.gz]

To restore the above compressed backup file we need to do the following:

gunzip [pickawebhproc.sql.gz]  | mysql -u root –p pickaweb


It’s a great built-in command line tool to restore data from CSV, txt, xml, access etc  file to MySQL database.

The general syntax for mysqlimport is

mysqlimport [options] db_name file_name

In the db_name we give the database name where we want to import data to. The filename can be CSV, txt file. It can only import data file not sql format file.

Mysqlimport has lot of options. Some of the most used options are:

–ignore-lines=n – ignores first n line of data

–columns=col_list – listing columns in the table according to the col_list

–lock-tables, -l – lock the table before importing data

–fields-terminated-by=str – separating the data into column by the character given

–lines-terminated-by=str – instructs the separation of line by the character

Let’s show you an example of how to import txt data using sqlimport into new database we will create in our MySQL server.

At first let’s get into the sql prompt by typing

mysql -u root -p

Now create new database import where we will import data from text.


We validate the import database existences by issuing SHOW DATABASES; command to see

Now let’s create table inside the import database and we will add in three filed inside the database.

First we select import database by use import; command

Then we create table inside the database by following command:

create table employee


userno int,

username varchar(15),

post varchar(10)


Note: We can use uppercase or lowercase inside MySQL prompt as its SQL statement and in SQL though uppercase is recommended, lowercase also works. Make sure you end each statement by semicolon. Also all the dql command needs to be typed inside mysql shell prompt and all other command shown before is under Ubuntu shell prompt.

Now lets create text file name employee.txt to import data into import database.

Note: Since the text file we create need to match the table name we created in the import database hence the text file name should be same as the table name created inside the database we are trying to import.

We create txt file by following command:

touch employee.txt

Then we insert following tab delimitated texts inside the text file by opening the tect file with VI editor.

vi employee.txt

Paste in the following data

100     John Doe        DBA

200     John Smith      Sysadmin

300     Raj Patel       Developer

Close and save.

Now we import the text data into our import database by the following command:

mysqlimport -u root -p –local import employee.txt

Now we will see the 3rows copied text been showed which implies successful import.

Now to check whether our import database employee table is populated by the employee information in the text file we need to get into the mysql prompt and run SQL query on the import database table.

We first get into the MySQL by typing:

mysql -u root –p

Then we load import table by use command:

Use import;

Now get all the employee information from the employee table by making following query:

select * from employee;

We see text information has been successfully imported inside import database which we can see in the following image:


Fig-29: mysqlimport: importing text document into database.

Backing up mysql automatically:

We can backup mysql database automatically with the help of one utility named automysqlbackup.This tool keeps the headache of administrator away by automatically backing up mysql database daily, weekly and monthly basis.

For installing automysql we type in the following command:

sudo apt-get install automysqlbackup

Run it by typing following;

sudo automysqlbackup

We can configure its configuration file which is located at /etc/default/automysqlbackup

We open the configuration file by

sudo vi /etc/default/automysqlbackup

We have to look at the following bold part of the configuration as follow […]

# Host name (or IP address) of MySQL server e.g localhost



# List of DBNAMES for Daily/Weekly Backup e.g. “DB1 DB2 DB3”

# The following is a quick hack that will find the names of the databases by

# reading the mysql folder content. Feel free to replace by something else.

#DBNAMES=”db_ispconfig web1 web2 web3″

DBNAMES=`mysql –defaults-file=/etc/mysql/debian.cnf –execute=”SHOW DATABASES” | awk ‘{print $1}’ | grep -v ^Database$ | grep -v ^mysql$ | grep -v ^performance_schema$ | grep -v ^information_schema$ | tr \\\r\\\n ,\ […]

# Backup directory location e.g /backups

# Folders inside this one will be created (daily, weekly, etc.), and the

# subfolders will be database names.



# Email Address to send mail to? ([email protected])

MAILADDR=”[email protected]



DBHOST here is localhost. If we want to backup remote database we need to type in the remote hostname here. But as we mentioned earlier remote hostname should have its mysql port opened.

DBNAMES will find all the database inside the server and it can be one to many databases.

BACKUPDIR is where the   automysqlbackup will keep their backups.

Let’s look at what is inside the /var/lib/automysqlbackup by ls into it as follows:

ls -l /var/lib/automysqlbackup

We will see there is three directory for creating daily, weekly and monthly backup.

drwxr-xr-x 4 root root 4096 Jun 27 22:21 daily

drwxr-xr-x 2 root root 4096 Jun 27 22:21 monthly

drwxr-xr-x 4 root root 4096 Jun 27 22:21 weekly

We will also see the two database created earlier is under the each of the above directories.

AutoMySQLBackup will back up our databases and the tables and compress data with gzip hence the saved file will be in .gzip file.

If we get into the cd /var/lib/automysqlbackup/daily folder you will see there is two subdirectories according to the two database we created earlier named: import & pickaweb.

And further cd into those subdirectories we will see the backup of those two databases has been created trailing the today’s day Sunday. Also we see the file has been compressed as gzip as we can see from the following picture:


Fig-30: automysqlbackup file

We can schedule this automatic backup by adding this to cron job of our Ubuntu by following command:

sudo crontab –e

It will give us option to open it with nano.

We open it and add following line to schedule our databases backup every night at midnight.

0 0 * * * /usr/sbin/automysqlbackup

This will make sure we do not have to manually run automysqlbackup everytime we want to run the backup.


Back up MySQL with mysqlhotcopy:

Mysqlhotcopy is built in perl script from mysql server to backup databases.  The way it works is by locking the table at first, then flushing the table and copy the data and unlocking the table in the end.

General syntax for mysqlhotcopy is:

mysqlhotcopy [options] db_name /path/to/new_directory

We can backup single database or multiple databases just like mysqldump and we can save it to current directory or directory mentioned on the path.

Let’s copy our import database to the Ubuntu desktop directory. We can do that by following command:

mysqlhotcopy -u root -p lamp1234  import /home/ubuntu/Desktop –allowold –keepold

If we see in the following picture in yellow part the backup copy of import databases has been done.


Fig-31: mysqlhotcopy in action

We used two options here

-allowold – will keep the old back up of import backup in the directory we mentioned. If it finds the old backup file of import database it will keep the old database file to import_old.

-keepold- This options keeps the old copy of the import database.

There are lot other options for mysqlhotcopy. We can have look at it by seeing the doc file with perdoc asfollows:

perldoc mysqlhotcopy

Some other options allowed are:

–flushlogs – it will flush all the logs after copying has been done

-debug- set this flag for debugging information.

–addtodest – it will not rename the directory if the target directory exists.

–regexp- it will copy the database name coming from the regular expressions.

–socket=path – connecting to localhost.

–tmpdir=path – path to temporary directory

Every database tables has three files *.frm, *.MYD and *.MYI. Also the dp.opt file which is database parameter file.

The way we restore the database from mysqlhotcopy is just by copying the backup files to the /var/lib/mysql/(database name) directory.  Before restoring the files which is copying the files to mysql database directory it’s recommended to stop mysql server. After copying finishes restart the mysql server with following command:

service mysqld stop

service mysqld start

Increasing MySQl server efficiency by MySqlTuner:

mysqlTuner is perl script which can increase our mysql server’s efficiency and performances.

At first let’s install it by

sudo apt-get install mysqltuner

Let’s run it by issuing:


It will ask for our mysql credentials as follows:

Please enter your MySQL administrative login:

Please enter your MySQL administrative password:

We give our root login and password and it will show general statistics of our mysql server’s health as shown in the image below:


Fig-32: mysqltuner status server health and recommendations.

As we can see in the output below it give us nice recommendation which we can make changes by going into our my.cnf file which is located at /etc/mysql/my.conf


——– Recommendations —————————————————–

General recommendations:

    Run OPTIMIZE TABLE to defragment tables for better performance

    Enable the slow query log to troubleshoot bad queries

    When making adjustments, make tmp_table_size/max_heap_table_size equal

    Reduce your SELECT DISTINCT queries without LIMIT clauses

Variables to adjust:

    query_cache_limit (> 1M, or use smaller result sets)

    tmp_table_size (> 16M)

    max_heap_table_size (> 16M)

Keeping the value not too much or not too low is generally recommended. By testing out with different values one can find out the perfect values for their server. After making any changes to the my.conf file we need to restart our mysql server to take any changes into effect.

We restart our mysql server by typing:

/etc/init.d/mysql restart

Or by   sudo service mysql restart

Installing Rsyslog for monitoring MySQL log:

Rsyslog is open source utility for robust logging for MySQL. We can install Rsyslog for better managing our logging for MySQL

Let’s install Rsyslog by typing:

sudo apt-get install install rsyslog*

If you get can’t locate package error we need to type in following command to add in necessary repository

sudo add-apt-repository ppa:adiscon/v8-devel

Then we update and upgrade our server by typing:

sudo apt-get update && sudo apt-get upgrade

Now if we want to install Rsyslog we can by typing:

sudo apt-get install rsyslog

Let’s install some dependencies as well by typing as follows:

apt-get install rsyslog rsyslog-mysql unzip zip binutils cpp fetchmail flex gcc libc6-dev libpcre3 libpopt-dev lynx m4 make ncftp nmap openssl perl perl-modules zlib1g-dev autoconf automake1.9 libtool bison autotools-dev g++ mysql-server mysql-client libmysqlclient15-dev apache2 apache2-doc apache2-mpm-prefork apache2-utils libexpat1 ssl-cert libapache2-mod-php5 php5 php5-common php5-curl php5-dev php5-gd php5-idn php-pear php5-imagick php5-imap php5-json php5-mcrypt php5-memcache php5-mhash php5-ming php5-mysql php5-ps php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xslng

It will ask for Rsyslog admin user password and Rsyslog application user password. We keep it as lamp1234 as same as our root MySQL password for our guide purposes. You should keep it different.

Now we need to configure the Rsyslog server configuration file and make it listen to port 1514

We type in following:

sudo vim /etc/rsyslog.conf

Now add in the following line in the configuration file:

$ModLoad ommysql


*.* :ommysql:,<SyslogDatabase>,<rsyslogUserName>,<rsyslogUserPassword>

And add the following line as well:

# provides TCP syslog reception

$ModLoad imtcp

$InputTCPServerRun 1514

$Modload imudp

$UDPServerRun 1514

Now restart the rsyslog server by typing:

/etc/init.d/rsyslog restart

Now let’s see whether our rsyslog is listening to port 1514 we define earlier in the configuration file by showing listening port on our server

netstat -ntap

We see the result in the following result that our rsyslog is listening on port 1514:


tcp        0      0     ESTABLISHED 1887/xrdp

tcp        0      0     ESTABLISHED 1887/xrdp

tcp        0      0         TIME_WAIT   –

tcp        0    432     ESTABLISHED 7046/sshd: ubuntu [

tcp        0      0         TIME_WAIT   –

tcp6       0      0 :::22                   :::*                    LISTEN      1766/sshd

tcp6       0      0 ::1:631                 :::*                    LISTEN      19995/cupsd

tcp6       0      0 :::1514                 :::*                    LISTEN      34022/rsyslogd

tcp6       0      0 :::80                   :::*                    LISTEN      30071/apache2

tcp6       0      0 ::1:46515               :::*                    LISTEN      9283/java

tcp6       1      0 ::1:53648               ::1:631                 CLOSE_WAIT

We see in bold line apache2, mysqld and rsyslog in listening on their designated port. Sweet!!!

Now let’s install log analyzer for our second virtual host pciakweb.lamp2

First we need to install latest LogAnalyzer inside the /usr/local/src directory

So let’s get into the above directory and download latest Log analyzer which is as of this writing 3.6.6

We type in following:

cd /usr/local/src

wget http://download.adiscon.com/LogAnalyzer/LogAnalyzer-3.6.6.tar.gz

Let’s extract the tar package by following command:

tar zxvf LogAnalyzer-3.6.6.tar.gz

Now lets move the LogAnalyzer src file into our pickaweb.lamp2 public folder:

mv LogAnalyzer-3.6.6/src/* /var/www/pickaweb.lamp2/public_html

Note: Use sudo if you working under normal user account.

Let’s change the user rights for apache for our public folder where we move the LogAnalyzer source file

chown www-data:www-data -Rf /var/www/pickaweb.lamp2/public_html/*

We need to own the public folder

Now copy the LogAnalyzer contrib folder into our public folder:

[email protected]:/usr/local/src# cp LogAnalyzer-3.6.6/contrib/*  /var/www/pickaweb.lamp2/public_html

We copy and move LogAnalyzer file to our pickaweb.lamp2 public folder from being inside the /usr/local/src folder where we installed LogAnalyzer originally as show on above command.

Now lets get into the picakweb.lamp2 public folder by cd into it with following command:

cd /var/www/pickaweb.lamp2/public_html

Now we need to run the configure.sh file of our LogAnalyzer which is inside our public_html folder.

sudo  ./configure.sh

Now if we open our browser and browse to picakweb.lamp2/install.php it will show us LogAnalyzer installation page from here which we will install LogAnalyzer graphically as shown below:


Fig -33: LogAnalyzer installation page


Let’s install it page by page by selecting next next and when we finish we might see screen saying syslog file is not readable if it happens we need to add www-data group we mad inside admin group by getting into /etc/group by following command:

sudo vim /etc/group

Add following line and close and save it


Reload Apache

service apache2 reload

Now if we reload the LogAnalyzer page we will not see the error hopefully. Now we will not see and syslog data as we haven’t told syslog to pass the data to syslog server listening on port 1514

So we need to configure /etc/rsyslog.conf file and add following line under global directories section.

$ActionQueueType LinkedList # run asynchronously

$ActionQueueFileName fwdRule1 # unique name prefix for spool files

$ActionQueueMaxDiskSpace 1g # 1gb space limit (use as much as possible)

$ActionQueueSaveOnShutdown on # save messages to disk on shutdown

$ActionResumeRetryCount -1 # infinite retries if host is down

Also we add in the following line under default permission for log files directory:

# Dump all messages to the remote logging server through

*.* @@LogAnalayzerIP:1514

Now if we restart our rsyslog server :

/etc/init.d/rsyslog restart

And now if we refresh our pickaweb.lamp2 browser window we will see syslog message populating in our LogAnalyzer window as follows:


Fig-34: LogAnalyzer syslog message

We can also generate report by selecting report tab on top bar and we following report:


Fig-35: LogAnalyzer Report


So we have installed and configure MySQL server and we tried to show you how to secure it as well as managing log information in more efficient manner with rsyslog and LogAnalyzer utitlity.

Here are the general tips to keep our MySQL server secure:

  • Clean our history file like .mysql_history as it often has MySQL password also we need to remove bash_history file which contains our command line history.
  • We need to disable Load data local file so that when an attacker gets hold of our MySQL cannot read our local file.
  • We should try to run our MySQL server and client in non-default port so it’s not easily guessable by attacker to run attacks on to.
  • Make sure the my.conf file is not writable so the hacker cannot write to it and change our root password.

Install and Configure PHP Support for our LAMP Server

For installing PHP support for our LAMP server we need to install PHP and all its associated modules by the following command:

sudo apt-get install php5 php5-mysql php-pear php5-gd  php5-mcrypt php5-curl

For mysql support in php we installed php5-mysql module.

We need to restart our apache server by following command:

service apache2 restart


Verifying Our PHP installation:

Now let’s create simple php file and check by browsing that .php file in order to see whether our server can run php file or not.

Let’s create info.php file in our pickaweb.lamp1 virtual host’s public_html file.

Here before we had index.html file.

We at first create .info.php file in var/www/pickaweb.lamp1/public_html by following command:

vi var/www/pickaweb.lamp1/public_html

It opens info.php file and we paste in following lines:




Now if we go to our browser and look for this info.php file by typing pickaweb.lamp1/info.php in our browser’s URL we will see we will be presented with php information page where it says apache2.0 handler and if we go further we see all the module installed and the mysql support all this that we installed and configured earlier.


Fig-36: Successful installation of PHP support.



Xcache install for optimizing PHP:

Xcache is a utility for better optimizing and caching PHP code. It will accelerate the speed of our PHP by some times.

Let’s install and configure it.

We first install it by following command:

apt-get install php5-xcache

The xcache configuration file is in xcache.ini file we can configure it by following command:

sudo vi /etc/php5/conf.d/xcache.ini

Whenever we configure configuration file we need to restart apache server to take its effect.

Restarting apache by following command:

/etc/init.d/apache2 restart

We can verify apache PHP by typing following command:

php –v

We will see the following output:

PHP 5.5.9-1ubuntu4.9 (cli) (built: Apr 17 2015 11:44:57)

Copyright (c) 1997-2014 The PHP Group

Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

    with XCache v3.1.0, Copyright (c) 2005-2013, by mOo

    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies

    with XCache Optimizer v3.1.0, Copyright (c) 2005-2013, by mOo

    with XCache Cacher v3.1.0, Copyright (c) 2005-2013, by mOo

    with XCache Coverager v3.1.0, Copyright (c) 2005-2013, by mOo


And as we saw before we can verify php by making info.php file in var/www/html or virtual host public html

Xcache Admin Panel for PHP:

Xcache has admin panel but normally it is disabled. You need to set up password which is md5 hash password and after generating the password you need to set it under Xcache.ini directory inside Xcache.ini file.

Let’s create the MD55 hash password first by typing as follows:

echo -n “typeyourpassword” | md5sum

We get the following output:


Lets open the Xcache.ini file by typing :

vi /etc/php5/mods-available/xcache.ini

Now lets make following changes by putting the MD5 generated password in password line under the Xcache.admin directory as show below in the bold part:


;; non-Windows example:

extension = xcache.so

;; Windows example:

; extension = php_xcache.dll



xcache.admin.enable_auth = On

 Configure this to use admin pages

 xcache.admin.user = “mOo”

 xcache.admin.pass = md5($your_password)

 xcache.admin.pass = “923557d0916ee875d06a38a66e461b76”



; ini only settings, all the values here is default unless explained


; select low level shm implemenation

xcache.shm_scheme =        “mmap”

; to disable: xcache.size=0

; to enable : xcache.size=64M etc (any size > 0) and your system mmap allows

xcache.size  =               60M

; set to cpu count (cat /proc/cpuinfo |grep -c processor)

xcache.count =                 1

; just a hash hints, you can always store count(items) > slots

xcache.slots =                8K

; ttl of the cache item, 0=forever

xcache.ttl   =                 0

; interval of gc scanning expired items, 0=no scan, other values is in seconds

xcache.gc_interval =           0


Now we need to copy the whole directory of Xcache inside the /var/www/html or /var/www if we are using default directory if not we need to copy it to our virtual host public_html directory as follows:

cp -a /usr/share/xcache/htdocs /var/www/pickaweb.lamp1

Now if we browse with our browser as follows:

http://localhot/xcache or http://localhost/admin


http://pickaweb.lamp1/admin or http://pickaweb.lamp1/xcache

We will see the Xcache admin page asking for the user and password which we set up earlier in the Xcache.admin directory.


Testing MySQL Connection with PHP:

For testing MySQL connection with our PHP we need create file inside our virtual hosts public_html directory or if some is working with default directory or website inside /var/www/html directory.

Let’s create the phpmysql.php file by following command in the above directory:

sudo touch /var/www/html/phpmysql.php

Let’s open the file by vi as follows:

vi /var/www/html/phpmysql.php

And paste the following line in the file except in the password line we give the root mysql password we set before in our case lamp1234


$con = mysql_connect(“localhost”,”root”,”lamp1234″);

if (!$con)


 die(‘Could not connect: ‘ . mysql_error());




 echo “Congrats! connection established successfully”;




Now if we open the browser and type in http://pickaweb.lamp1/phypmysql.php we will see congrats connection established successfully shown.

Installing and configuring phpMyAdmin:

Let’s install phpmyadmin which will control our mysql server GUI based for web developer.

Let’s install by following command:

sudo apt-get update

sudo apt-get install phpmyadmin

We will at first be prompted for choosing which server we choose aapchge2 server. Then we will be prompted for database administrator’s password which we keep it same as lamp1234 for testing purpose also next step we will be prompted for phpMyAdmin application password which we keep same too.

After successful typing in the server the phymyadmin will be installed in our server.

The phpMyAdmin configuration file is inside the /etc/apache2/conf-enabled/ directory.

Now let’s enable the php5-mycrypt extention by typing as follows:

sudo php5enmod mcrypt

We need to go inside the apache2.conf file and in the include directory under virtual host configuration in the following bold part add in the phpmyadmin config file as follows:

Include /etc/phpmyadmin/apache.conf


# Include of directories ignores editors’ and dpkg’s backup files,

# see README.Debian for details.


# Include generic snippets of statements

IncludeOptional conf-enabled/*.conf


# Include the virtual host configurations:

IncludeOptional sites-enabled/*.conf

Include /etc/phpmyadmin/apache.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Now we need to restart our apache server as always by typing

sudo service apache2 restart

Now lets access our GUI for phpmyadmin

So we go to the browser and we type in pickaweb.lamp1/phpmyadmin we will see the following picture giving us phymyadmin GUI access login page:


Fig-37: phpMyAdmin login page


Now let’s give user root and password as we set up during installation which is similar to our mysql root password lamp1234 we will be given phpmyadmin user interface as follows:


Fig-38: phpMyAdmin user interface

 Securing phpMyAdmin:

Attacker is always looking out to attack your mysql server especially to get into your phpMyAdmin page. One of the way we can secure it is via the .htaccess file.

Let’s install another utility names:

sudo apt-get install apache2-utils

This will help us work with htpasswd which we will use to secure our phpMyAdmin

We will use .htaccess for authenticating user to the phpmyadmin

Let’s first create .htpasswd file for the user we want to give access to.

We do this by typing following command:

sudo htpasswd -c /etc/phpmyadmin/.htpasswd pickaweb

We will create pickaweb user it will ask for the password we use lamp1234

If we want to add more user we can do so by following command by typing the username in place of anyname as follows:

sudo htpasswd /etc/phpmyadmin/.htpasswd anyname


Now we need to configure apache.conf file to allow .htaccess to override. We do that by configuring apache.conf file which is inside the /etc/phpmyadmin directory

So we edit the apache.conf file by typing as follows:

sudo vi /etc/phypmyadmin/apache.conf

Then we need to add in the following bold line under <Directory /usr/share/phpmyadmin> directory

Alias /phpmyadmin /usr/share/phpmyadmin


<Directory /usr/share/phpmyadmin>

Options FollowSymLinks

DirectoryIndex index.php

AllowOverride All

<IfModule mod_php5.c>

AddType application/x-httpd-php .php


php_flag magic_quotes_gpc Off

php_flag track_vars On

php_flag register_globals Off

php_admin_flag allow_url_fopen Off

php_value include_path .

php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp

php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/javascript/





Now we need to create .htaccess file inside the /ect/phpmyadmin directory which will make the .htpasswd to make it work.

We do that by following command

sudo nano /usr/share/phpmyadmin/.htaccess

And we have to paste following line inside it and the save and close.

AuthType Basic

AuthName “Restricted: Authentication Required”

AuthUserFile /etc/phpmyadmin/.htpasswd

Require valid-user

It says the authentication type to be basic. Authname will show the message when logging into the phpmyadmin

Then it will be promoted to the log and password so when the user give login and password information it will matched with the user created and password at the time of .htpasswd file creation.

Now let’s restart the apache server to get all this configuration to work.

sudo service apache2 restart

So now let’s go to like before to our phpmyadmin GUi page by browsing into our firefox browser:

http://pickaweb.lamp1/phpmyadmin it will prompt you for authentication as follows:


Fig-39: User authentication Prompt at phypadmin login page

Now let’s give the login and password we created for pickaweb user. We will be then presented with the phpmyadmin login page which we can login by root username and password like we did in the beginning.

It’s not recommended to use root account to log into the phpmyadmin login page. So we should create other user during the installation of the phpmyadmin.


Restrict PhpMyAdmin Login by IP:

We can Filter Phpmyadmin login page access by IP address as well.

For that we need to configure apache.conf file which is inside the /etc/phpmyadmin directory

So we edit the apache.conf file by typing as follows:

sudo vi /etc/phypmyadmin/apache.conf

Then we need to add in the following bold line under <Directory /usr/share/phpmyadmin> directory

Alias /phpmyadmin /usr/share/phpmyadmin


<Directory /usr/share/phpmyadmin>

Options FollowSymLinks

DirectoryIndex index.php

AllowOverride All

Order Allow , deny

          Allow from x.x.x.x

<IfModule mod_php5.c>

AddType application/x-httpd-php .php


php_flag magic_quotes_gpc Off

php_flag track_vars On

php_flag register_globals Off

php_admin_flag allow_url_fopen Off

php_value include_path .

php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp

php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/javascript/





We can give whatever address we want in place of X.X.X.X to allow connection from that IP only to our PhpMyAdmin login page.


USE SSL while Logging Into PhpMyAdmin Page:

When we log in to Mysql server via PhpMyAdmin page we give our username and password. Attacker can sniff the data if they get in to the network and get our MySQL password. The way we can prevent this is by Forcing apache to use SSL certificates while logging into the PhpMyAdmin login page.

After installing the SSL certificates into the apache webserver to use it with the website we can tell PhpMyadmin to use SSL every time user ties to log into the PhpMyAdmin page.

For this to happen we need to configure the config.inc.php file which is located in our server at /etc/phpmyadmin/config.inc.php

So we open the above configuration file for editing by typing the command as follows:

vi /etc/phpmyadmin/config.inc.php

Now under server configuration directory just add the line in bold line shown below:


 * Server(s) configuration


$cfg[‘ForceSSL’] = ‘true’;

$i = 0;

// The $cfg[‘Servers’] array starts with $cfg[‘Servers’][1].  Do not use $cfg[‘Servers’][0].

// You can disable a server config entry by setting host to ”.



Close and exit save the file.

Now restart the server by typing as follows:

sudo service apache2 restart

Another way we can do it is by the help of .htaccess file. We can add the following line in .htaccess file

RewriteEngine On

RewriteCond %{SERVER_PORT} !^443$

RewriteRule ^/directory(.*)$ https://%{HTTP_HOST}/directory$1 [L,R]


Password protecting Our Website:

Now that we know how to use. Htpasswd file why not we password protect our website like pickaweb1. We can do that by creating user account in htpasswd file and creating it inside following in our /var/www/pickaweb.lamp1

We do that by typing following:

sudo htpasswd -c  /var/www/pickaweb.lamp1/.htpasswd pickaweb1

Here we are creating user name pickaweb1

Now we need to make changes to the pickaweb.lamp1.conf file inside the /etc/apache2/site-available directory

We open the above configuration file by typing

vi etc/apache2/sites-available/ pickaweb.lamp1.conf

We add in the following line in the configuration file:

  <Directory “/var/www/pickaweb.lamp1/public_html”>

AuthName “Restricted”

AuthType Basic

AuthUserFile /var/www/pickaweb.lamp1/htpasswd

require valid-user



Its will look into our .htpasswd file we created earlier. As we have created the username pickaweb1 above and password we will need it as we browse for our pickaweb.lamp1 webiste will ask for login.

Let’s restart our apache2 server by typing the following:

sudo service apache2 restart

Now let’s go to our browser and in the URL we type: pickaweb.lamp1 and we will see we are prompted with user verification login screen as follows:


Fig- 40: Password Protecting Our Website.

Now we have secured our PhpMyAdmin. We can secured our PhpMyAdmin by restricting users, creating user account with complex password always using SSL for PhpMyAdmin login etc.


In this long journey we finished installing our LAMP server by installing individually the Apache webserver, MySQL server and last of all PHP. We showed you how to install, configure and secure each of the components of LAMP server with our demo pickaweb user, pickaweb websites and databases etc.

We can certainly install LAMP server by just one command by following cool command in Ubuntu server:

sudo apt-get install lamp-server*

It will install by default Apache2, Mysql 5, and PHP5 in our Ubuntu server. But the best way is installing one by one as by this way we can better configure our LAMP server well.

Leave a Reply

Your email address will not be published. Required fields are marked *