SlideShare uma empresa Scribd logo
1 de 42
Definitive Guide to Setting up a LAMP Server using Open
Source Software
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
address 89.187.86.196
netmask 255.255.255.0
broadcast 89.187.86.255
network 89.187.86.0
gateway 89.187.86.1
Here we made our primary network adapter eth0 from DHCP to static and set it up with static
IP address of 192.168.1.102
In our lab network its in 192.168.1.0 network so the broadcast address will be 192.168.1.255
and the default gateway which is our router address is : 192.168.1.1
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
Add:
nameserver 89.187.86.1
nameserver 8.8.8.8
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.
# User privilege specification
root ALL=(ALL:ALL) ALL
PickawebLAMP ALL=(ALL:ALL) ALL
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 127.0.0.1 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
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 127.0.0.1 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 needtotype insome simpleHtml code sothatitpopulatesinourapache webserverwhenwebrowse
for this index.html page.
So we type in as follows:
<html>
<head>
<title>www.pickaweblamp1.com</title>
</head>
<body>
<h1>Welcome To pickaweblamp1 website</h1>
</body>
</html>
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
<html>
<head>
<title>www.pickaweblamp2.com</title>
</head>
<body>
<h1>Welcome To pickaweblamp2 website</h1>
</body>
</html>
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.lamp
1.conf
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/pickaweb.lamp
2.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 webmaster@localhost
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 webmaster@pickaweblamp1.com
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 127.0.0.1 is pointing toward host name
localhost.
That’s why when we type in hostname its actually refereeing to 127.0.0.1 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 127.0.0.1
So we edit our /etc/hosts file by typing:
sudo vi /etc/hosts
Then we add
127.0.0.1 pickaweb.lamp1
127.0.0.1 pickaweb.lamp2
Under 127.0.0.1 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.
Fig-12: Testing our Virtual Hosts
We hosted two virtual hosts in our localhosts loopback IP address 127.0.0.1 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 127.0.0.1 ::1
Allow from none
</Location>
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 89.187.86.0/24 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 89.187.86.1. 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
add_head
combine_css
combine_javascript
convert_meta_tags
extend_cache
fallback_rewrite_css_urls
flatten_css_imports
inline_css
inline_import_to_link
inline_javascript
rewrite_css
rewrite_images
rewrite_javascript
rewrite_style_attributes_with_url
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
LISTEN 89.187.86.5:80
LISTEN 89.187.86.10.:2031
Here we specified IP address 89.187.86.5 to accept connection on port 80 and 89.187.86.10 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 webmaster@pickaweblamp1.com
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
</VirtualHost>
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 webmaster@pickaweblamp1.com
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
</VirtualHost>
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
</Directory>
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 webmaster@pickaweblamp1.com
DocumentRoot /var/www/pickaweb.lamp1/public_html
<Directory />
Options FollowSymLinks Indexes
AllowOverride None
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
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
Nowwe can configure deflate twoways. We can explicitlymentionthe file we wantto include or don’t
want to include inthe MIME type.We alsocan enable mod_deflate forwhole apache2serverorjust for
our eachof the virtual hostswe createdearlier. We canconfigure inthe golabrapache2configurationfile
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 wantto compressall the typesbutkeepingasidessomeof the few wecan dosoby addingfollowing
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 followingline 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
Thistell browsertocompress dataforotherfileincludinghtml aspreviouslybrowserusedtosupport only
compressing HTML document.
Some of the file that we think need to be compressed are as follows:
text/html
text/plain
text/xml
text/x-js
text/javascript
text/css
application/xml
application/xhtml+xml
application/x-javascript
application/javascript
application/json
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 maxrequestsperchildinstructsthe apache serverastohow manyrequestsanindividual childprocess
will handle. Whatevernumberwe puthere the childprocesswillserve thatmanyrequestsandafter that
it stops.Butif we set itto 0 itwill keepacceptingthe requestsanditwill neverexpire. Itisbettertokeep
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
.Workerand the preforkare the two maintype of MPM inapache. The wayworkeroperatesisit creates
extra threads on top of child process to handle each new connections where the prefork MPMcreates
newprocessforeachnew connections.One caneasilyswitchbetweenthesetwoandfindoutwhichsooth
them best.
One of the easiest way to find out which MPMone server is running is by issuing
aptitude search apache2-mpm-
As we can see in the followingpicture ourserverwe have fourMPMavailable forour serveras indicated
by the letter P preceding it. If it was installed it would have I letter preceding it.
Fig-20: Available MPM in apache
Anotherwayone canfindoutisbyissuing apache2ctl -lgwhichwillshowcompiledmoduleswithinapache
server. In our case it will now show any MPMas 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 MPMis been installed as shown in the picture below
Fig-21: Installed MPM in apache
We now have to enable any of the MPMwe 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 MPMin our server we type in
ls /etc/apache2/mods-available/mpm* and we see we have three MPM event, worker, and prefrok
available
/etc/apache2/mods-available/mpm_event.conf
/etc/apache2/mods-available/mpm_event.load
/etc/apache2/mods-available/mpm_prefork.conf
/etc/apache2/mods-available/mpm_prefork.load
/etc/apache2/mods-available/mpm_worker.conf
/etc/apache2/mods-available/mpm_worker.load
Now if we want to find out the active MPMmodule 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 MPMmodule 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
/etc/apache2/mods-enabled/mpm_prefork.conf
We the default configuration is such as follows:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
The Startserversindicateshowmanychildprocessthe serverwillinitiate whenitstarts.Here we setit 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.
Everytime hostnameneedstobe matchedtoIPaddresstheapache serverhastogoforDNSlookupwhich
createsextraoverhead.It’srecommendedtokeepthe DNSlookupoff.BydefaultDNSlookupisdisabled.
Evenwhenwe wantto use allowanddenywe shoulduse IPaddressinsteadof hostname whichwillstop
apache to go for DNS lookup and use up extra processes.
Configuring Content Negotiation:
Contentnegotiationisthe wayapache servercandeliversthe contenttothe browserthe wayitlikes.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.
TypeMaps:
To configure TypeMaps in a directory where we want content negotiations we needto create .htaccess
file and include the following line
AddHandler type-map var
In the var extensionwe canuse index.html.varwhichisapache bydefault. We ca explicitlylink with the
Variantlike index.html.varorwe can linkto the more defaultindex type bydeclaringall in the directory
Index.
DirectoryIndex index.html.var index.html index.php
MultiViews:
InMultiviewsonecanenableitinsidethe .htaccessfilebyaddingfollowinglinetowhicheverthedirectory
we want multiviews to be enabled:
Options +MultiViews
We can setMultiViewsforcontenttype likeservingXhtmlforthe useragentwhosupportitif notitserves
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 qualityso that oldbrowsers will
get .html
Above configurationinstructsapache tointerpretthe fileaccordingtoitsextensions.Like ifbrowserwants
to getindex page fromapache if thebrowsersupportsxhtmlitwill serve theindex.xhtml page ifnotitwill
serve the index.html page.
We cansetuppreferredlanguagewithMultiViewssothatitcannegotiateautomaticallywiththe 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 andindex.de.html.Whateverthe useragent’sdefaultlanguage 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 serverif workingwithdynamicpagescantake significantamountof memoryanditkeepusingup
the memoryuntil itfullyloadsthe dynamiccontents.Itistrue evenforapage withonlyimagesasittreats
it like dynamic page and in processallocate lots of memory for work that it does not need that much of
memory.Thissignificantlyreducesthe apache performances.If we can set up apache serverto 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 thisbyredirectingstaticpage requeststo lightweightfrontserverandmore intense
dynamicpages to back endheavyserver. We canachieve thisbyMod_proxymodulesandrewrite
module.
For example we cansetuplightweightapache serveronone port80 and heavyweightserveronother
port 5500 so that we can redirectstaticpagesand dynamicpagesaccordingly.
Thenour configurationfilewill be:
ProxyPassReverse / http://%{HTTP_HOST}:5500/
RewriteEngine on
RewriteCond %{REQUEST_URI} !.*.(gif|png|jpg)$
RewriteRule ^/(.*) http://%{HTTP_HOST}:8088/$1 [P]
Here we are instructingapache thatall the requeststobe sentto the backendserverlisteningonport
5500 exceptthe images. Thenwhenthe backendserverresponse itfirstgoestothe frontendserver
and thento the client.
Thisway we can isolate dynamicandstaticpage requestsaswell aswe can buildonthisconfiguration
and make the heavyrequesttobe forwardedtothe external serveraswell.
Unload UnnecessaryModules:
Apache serverworksbysetting module wise.Administratorcanchoose setof moduleshe wantsinhis
serverandenable it,tweakitthe wayhe wants. Modulesare compilesstaticallyanddynamically.
Staticallycompiledmoduleuse lessRAMbutdownside beingaddinganddroppingthe module needs
recompilingintoapache whereelsedynamicallyloadedmodulesdoesnotneedcompilingasitcan be
loadedbyLoadModule command .
Loadingunnecessarymoduleaddsextraloadtothe apache resourcessounloadingunnecessary
modulescanimprove the performancesof the apace server.
AllowOverride:
Allowoverride option indefault/etc/apache2/apche2.conf indirectory isnormallysettonone.If setto
none the apache serverlooksfor.htaccessfile ineachdirectoryittraverse.Forexample configuration
such as follows:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>Makes apache webservertolookforall the .htaccessfile ineachsubsequentdirectories
like /var, /var/www,/var/www/html if one requestlike/index.html ismade. Thisadditional lookup
slowsdownthe apache server.
So it’srecommendedtomake changestoas follows:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride ALL
Require all granted
</Directory>So that apache doesnot have to lookfor.htaccessfile ineachdirectory.If there isneed
for .htaccessfile inanydirectorymake itenable forthatparticulardirectoryonly.
We have to restartapache now to make the .htaccessfile active.
How to make user friendly URL in apache:
Lot of the time administratorwantstomake URL of website more userfriendly.Forexampleletslookat
followingURLof website:
http://www.pickaweblamp1.com/index.php?id=712
If we wantusernot to rememberthe trailingpartof the URL we can make it possible inapache with
Mod_rewrite module tosomethingsimplerlikebelow:
http://www.pickaweblamp1.com/712.html
Firstof all we needtoenable rewrite inapache byissuingfollowingcommand
sudoa2enmodrewrite
Thenwe restart apache server.
Once the rewrite module isactivatedwe needtoopenorcreate .htaccessfile inthe directorywe need
to applyrewrite module. Thiswillbe validforthe directorythe .htaccessfileresidesaswell asthe
subsequesntdirectoriesaswell.
With.htaccessfile we canmake changesper directorylevel withoutneedingtoconfigure the main
serverconfigurationfile.
We thencreate .htaccessfile tothe directorywe wantwithfollowingcommand
sudonano /var/www/pickaweb.lamp1/.htaccess
Nowwe want to make changestothe sitesforwhichwe are applyingrewrite module to.Sointhe site
available directorywe make changestothe default 000-default.conf file if we wantwholesite wise
configurationorif we wantper virtual hostwise configurationwe canchange to the virtual host
configurationfileinside the site-available directoryinourcase pickaweb.lamp1.conf or
pickaweb.lamp2.conf file.
We have to make the AllowOverride All inthe directory sectionof eitherthe pickaweb.lamp1.conf or
pickaweb.lamp2.conf to enable the .htaccessfile forpickaweb.lamp1orpickaweb.lamp2.conf.
If we wantwhole site tobe available forthisrewrite module we needtomake changestothe 000-
default.conf file.
Nowrestartthe apache servertotake itseffect.
So let’ssaywe want http://www.pickaweblamp1.com/index.php?id=712
URL to looklike more userfriendly http://www.pickaweblamp1.com/712.html
We needtoadd followingrule in the .htaccessfilethatwe made earlierinside
/etc/var/www/pickaweb.lamp1directory Options+FollowSymLinks
RewriteEngine On
RewriteRule ^id/([a-zA-Z0-9]+)/$index.php?id=$1
Here the
the [a-zA-Z0-9] takesanyuppercase of lowercase alphanumericletters.
• The asteriskinside the brackets isusedtomatchoccurences.
• ([a-zA-Z0-9]+) itwilltake all the alphaalphanumericof 1character
• The caret ^ means“start with”,meaningthe URLstarts withthe word “id”.
• The dollarsign$ meansthe URL will finishwithslashsign
• The $1 meansit will carrywhateverwaswritteninthe groupof bracketsbefore
Nowwe save the .htaccessfile andrestartthe apache server.
So nowclientsdonothave to memorize the URL as
http://www.pickaweblamp1.com/index.php?id=712
Whenthe clienttype inURL as http://www.pickaweblamp1.com/712.html it will requestabove URLin
the backendby the apache.
More reference onRewrite isavailableat:
http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Thisare the stepswe can take to optimize our apache serverandmake itfasterand Userfriendlyforthe
users.
Definitive guide to setting up a lamp server using open source software

Mais conteúdo relacionado

Mais procurados

Lamp Server With Drupal Installation
Lamp Server With Drupal InstallationLamp Server With Drupal Installation
Lamp Server With Drupal Installation
franbow
 
Ansible automation tool with modules
Ansible automation tool with modulesAnsible automation tool with modules
Ansible automation tool with modules
mohamedmoharam
 
Tutorial CentOS 5 untuk Webhosting
Tutorial CentOS 5 untuk WebhostingTutorial CentOS 5 untuk Webhosting
Tutorial CentOS 5 untuk Webhosting
Beni Krisbiantoro
 
Lamp technology
Lamp technologyLamp technology
Lamp technology
2tharan21
 
Web Server Administration
Web Server AdministrationWeb Server Administration
Web Server Administration
webhostingguy
 
Prabu apache installations
Prabu apache installationsPrabu apache installations
Prabu apache installations
Prabu Cse
 

Mais procurados (18)

L.A.M.P Installation Note --- CentOS 6.5
L.A.M.P Installation Note --- CentOS 6.5L.A.M.P Installation Note --- CentOS 6.5
L.A.M.P Installation Note --- CentOS 6.5
 
Lamp Server With Drupal Installation
Lamp Server With Drupal InstallationLamp Server With Drupal Installation
Lamp Server With Drupal Installation
 
2 how to-build_document_management_system
2 how to-build_document_management_system2 how to-build_document_management_system
2 how to-build_document_management_system
 
Its3 Drupal
Its3 DrupalIts3 Drupal
Its3 Drupal
 
Installing lemp with ssl and varnish on Debian 9
Installing lemp with ssl and varnish on Debian 9Installing lemp with ssl and varnish on Debian 9
Installing lemp with ssl and varnish on Debian 9
 
Apache1.ppt
Apache1.pptApache1.ppt
Apache1.ppt
 
Ansible automation tool with modules
Ansible automation tool with modulesAnsible automation tool with modules
Ansible automation tool with modules
 
Tutorial CentOS 5 untuk Webhosting
Tutorial CentOS 5 untuk WebhostingTutorial CentOS 5 untuk Webhosting
Tutorial CentOS 5 untuk Webhosting
 
Apache server configuration
Apache server configurationApache server configuration
Apache server configuration
 
Httpd.conf
Httpd.confHttpd.conf
Httpd.conf
 
Apache Presentation
Apache PresentationApache Presentation
Apache Presentation
 
Lamp technology
Lamp technologyLamp technology
Lamp technology
 
Web Server Administration
Web Server AdministrationWeb Server Administration
Web Server Administration
 
L5 swagger
L5 swaggerL5 swagger
L5 swagger
 
Web server installation_configuration_apache
Web server installation_configuration_apacheWeb server installation_configuration_apache
Web server installation_configuration_apache
 
Apache Web Server Setup 2
Apache Web Server Setup 2Apache Web Server Setup 2
Apache Web Server Setup 2
 
Prabu apache installations
Prabu apache installationsPrabu apache installations
Prabu apache installations
 
SquirrelMail for webmail
SquirrelMail for webmailSquirrelMail for webmail
SquirrelMail for webmail
 

Destaque

T Test For Two Independent Samples
T Test For Two Independent SamplesT Test For Two Independent Samples
T Test For Two Independent Samples
shoffma5
 
Dfd examples
Dfd examplesDfd examples
Dfd examples
Mohit
 
Sample Business Proposal Presentation
Sample Business Proposal PresentationSample Business Proposal Presentation
Sample Business Proposal Presentation
Daryll Cabagay
 

Destaque (12)

Camtasia Studio 4 Example
Camtasia Studio 4 ExampleCamtasia Studio 4 Example
Camtasia Studio 4 Example
 
Generic VSOE Lesson
Generic VSOE LessonGeneric VSOE Lesson
Generic VSOE Lesson
 
Famous Poet- Robert Frost
Famous Poet- Robert FrostFamous Poet- Robert Frost
Famous Poet- Robert Frost
 
Example Of Entrepreneur
Example Of EntrepreneurExample Of Entrepreneur
Example Of Entrepreneur
 
Difference WAMP and XAMPP
Difference WAMP and XAMPPDifference WAMP and XAMPP
Difference WAMP and XAMPP
 
Android ppt with example of budget manager
Android ppt with example of budget managerAndroid ppt with example of budget manager
Android ppt with example of budget manager
 
What does Information Literacy mean? Some examples from different disciplines
What does Information Literacy mean? Some examples from different disciplinesWhat does Information Literacy mean? Some examples from different disciplines
What does Information Literacy mean? Some examples from different disciplines
 
Electrodiagnostic Tests in Ophthalmology
Electrodiagnostic Tests in OphthalmologyElectrodiagnostic Tests in Ophthalmology
Electrodiagnostic Tests in Ophthalmology
 
Social Media Marketing Campaign PPT
Social Media Marketing Campaign PPTSocial Media Marketing Campaign PPT
Social Media Marketing Campaign PPT
 
T Test For Two Independent Samples
T Test For Two Independent SamplesT Test For Two Independent Samples
T Test For Two Independent Samples
 
Dfd examples
Dfd examplesDfd examples
Dfd examples
 
Sample Business Proposal Presentation
Sample Business Proposal PresentationSample Business Proposal Presentation
Sample Business Proposal Presentation
 

Semelhante a Definitive guide to setting up a lamp server using open source software

R hive tutorial supplement 1 - Installing Hadoop
R hive tutorial supplement 1 - Installing HadoopR hive tutorial supplement 1 - Installing Hadoop
R hive tutorial supplement 1 - Installing Hadoop
Aiden Seonghak Hong
 
Linux Webserver Installation Command and GUI.ppt
Linux Webserver Installation Command and GUI.pptLinux Webserver Installation Command and GUI.ppt
Linux Webserver Installation Command and GUI.ppt
webhostingguy
 
Power point on linux commands,appache,php,mysql,html,css,web 2.0
Power point on linux commands,appache,php,mysql,html,css,web 2.0Power point on linux commands,appache,php,mysql,html,css,web 2.0
Power point on linux commands,appache,php,mysql,html,css,web 2.0
venkatakrishnan k
 

Semelhante a Definitive guide to setting up a lamp server using open source software (20)

Installing Lamp Stack on Ubuntu Instance
Installing Lamp Stack on Ubuntu InstanceInstalling Lamp Stack on Ubuntu Instance
Installing Lamp Stack on Ubuntu Instance
 
Configuration of Apache Web Server On CentOS 8
Configuration of Apache Web Server On CentOS 8Configuration of Apache Web Server On CentOS 8
Configuration of Apache Web Server On CentOS 8
 
Project-make a public website server using raspberry pi
Project-make a public website server using raspberry piProject-make a public website server using raspberry pi
Project-make a public website server using raspberry pi
 
Apache web server tutorial for linux
Apache web server tutorial for linuxApache web server tutorial for linux
Apache web server tutorial for linux
 
Free ipa installation and cluster configuration, freeipa client connection
Free ipa installation and cluster configuration, freeipa client connectionFree ipa installation and cluster configuration, freeipa client connection
Free ipa installation and cluster configuration, freeipa client connection
 
Lumen
LumenLumen
Lumen
 
Install LAMP Stack in Linux Server OS and Hosting a Custom Domain .pptx
 Install LAMP Stack  in Linux Server OS and Hosting a Custom Domain .pptx Install LAMP Stack  in Linux Server OS and Hosting a Custom Domain .pptx
Install LAMP Stack in Linux Server OS and Hosting a Custom Domain .pptx
 
Its3 Drupal
Its3 DrupalIts3 Drupal
Its3 Drupal
 
Deploying your rails application to a clean ubuntu 10
Deploying your rails application to a clean ubuntu 10Deploying your rails application to a clean ubuntu 10
Deploying your rails application to a clean ubuntu 10
 
R hive tutorial supplement 1 - Installing Hadoop
R hive tutorial supplement 1 - Installing HadoopR hive tutorial supplement 1 - Installing Hadoop
R hive tutorial supplement 1 - Installing Hadoop
 
Linux Webserver Installation Command and GUI.ppt
Linux Webserver Installation Command and GUI.pptLinux Webserver Installation Command and GUI.ppt
Linux Webserver Installation Command and GUI.ppt
 
How To Install & Configure Varnish with Apache on Ubuntu
How To Install & Configure Varnish with Apache on UbuntuHow To Install & Configure Varnish with Apache on Ubuntu
How To Install & Configure Varnish with Apache on Ubuntu
 
Host a Web Application on an Apache Server while Running the Server on an EC2...
Host a Web Application on an Apache Server while Running the Server on an EC2...Host a Web Application on an Apache Server while Running the Server on an EC2...
Host a Web Application on an Apache Server while Running the Server on an EC2...
 
Configuring Your First Hadoop Cluster On EC2
Configuring Your First Hadoop Cluster On EC2Configuring Your First Hadoop Cluster On EC2
Configuring Your First Hadoop Cluster On EC2
 
Installing and configuring apache
Installing and configuring apacheInstalling and configuring apache
Installing and configuring apache
 
Setting Up a Cloud Server - Part 3 - Transcript.pdf
Setting Up a Cloud Server - Part 3 - Transcript.pdfSetting Up a Cloud Server - Part 3 - Transcript.pdf
Setting Up a Cloud Server - Part 3 - Transcript.pdf
 
Automating the Cloud with Terraform, and Ansible
Automating the Cloud with Terraform, and AnsibleAutomating the Cloud with Terraform, and Ansible
Automating the Cloud with Terraform, and Ansible
 
Power point on linux commands,appache,php,mysql,html,css,web 2.0
Power point on linux commands,appache,php,mysql,html,css,web 2.0Power point on linux commands,appache,php,mysql,html,css,web 2.0
Power point on linux commands,appache,php,mysql,html,css,web 2.0
 
Linux presentation
Linux presentationLinux presentation
Linux presentation
 
Cloud Automation with Opscode Chef
Cloud Automation with Opscode ChefCloud Automation with Opscode Chef
Cloud Automation with Opscode Chef
 

Último

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Último (20)

MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 

Definitive guide to setting up a lamp server using open source software

  • 1. Definitive Guide to Setting up a LAMP Server using Open Source Software 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:
  • 2. vi /etc/network/interfaces We add following lines into the file iface eth0 inet static address 89.187.86.196 netmask 255.255.255.0 broadcast 89.187.86.255 network 89.187.86.0 gateway 89.187.86.1 Here we made our primary network adapter eth0 from DHCP to static and set it up with static IP address of 192.168.1.102 In our lab network its in 192.168.1.0 network so the broadcast address will be 192.168.1.255 and the default gateway which is our router address is : 192.168.1.1 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.
  • 3. 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 Add: nameserver 89.187.86.1 nameserver 8.8.8.8 Fig-2: Channing the nameserver
  • 4. 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.
  • 5. 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. # User privilege specification root ALL=(ALL:ALL) ALL PickawebLAMP ALL=(ALL:ALL) ALL 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.
  • 6. 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
  • 7. 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 127.0.0.1 loopback address we will see apache page showing saying it work as how below in the picture.
  • 8. 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 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
  • 9. 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
  • 10. 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
  • 11. 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 127.0.0.1 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
  • 12. 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 needtotype insome simpleHtml code sothatitpopulatesinourapache webserverwhenwebrowse for this index.html page. So we type in as follows: <html> <head> <title>www.pickaweblamp1.com</title> </head> <body> <h1>Welcome To pickaweblamp1 website</h1> </body> </html> 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 <html> <head> <title>www.pickaweblamp2.com</title> </head>
  • 13. <body> <h1>Welcome To pickaweblamp2 website</h1> </body> </html> 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.lamp 1.conf sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/pickaweb.lamp 2.conf
  • 14. 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 webmaster@localhost 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
  • 15. 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 webmaster@pickaweblamp1.com 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
  • 16. 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 127.0.0.1 is pointing toward host name localhost. That’s why when we type in hostname its actually refereeing to 127.0.0.1 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 127.0.0.1 So we edit our /etc/hosts file by typing: sudo vi /etc/hosts Then we add 127.0.0.1 pickaweb.lamp1 127.0.0.1 pickaweb.lamp2 Under 127.0.0.1 localhost Then we save and exit.
  • 17. 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.
  • 18. Fig-12: Testing our Virtual Hosts We hosted two virtual hosts in our localhosts loopback IP address 127.0.0.1 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.
  • 19. 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
  • 20. 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 127.0.0.1 ::1 Allow from none </Location> 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 89.187.86.0/24 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 89.187.86.1. 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
  • 21. 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
  • 22. 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
  • 23. Default set of corefilters have lot of filters to name few such are add_head combine_css combine_javascript convert_meta_tags extend_cache fallback_rewrite_css_urls flatten_css_imports inline_css inline_import_to_link inline_javascript rewrite_css rewrite_images rewrite_javascript rewrite_style_attributes_with_url 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.
  • 24. 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.
  • 25. 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 LISTEN 89.187.86.5:80 LISTEN 89.187.86.10.:2031 Here we specified IP address 89.187.86.5 to accept connection on port 80 and 89.187.86.10 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
  • 26. 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 webmaster@pickaweblamp1.com 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 </VirtualHost> 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 webmaster@pickaweblamp1.com 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
  • 27. </VirtualHost> 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 </Directory> 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 webmaster@pickaweblamp1.com DocumentRoot /var/www/pickaweb.lamp1/public_html <Directory /> Options FollowSymLinks Indexes AllowOverride None </Directory>
  • 28. ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> 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.
  • 29. 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
  • 30. 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 Nowwe can configure deflate twoways. We can explicitlymentionthe file we wantto include or don’t want to include inthe MIME type.We alsocan enable mod_deflate forwhole apache2serverorjust for our eachof the virtual hostswe createdearlier. We canconfigure inthe golabrapache2configurationfile 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:
  • 31. Fig-19: Mod_deflate configuration If we wantto compressall the typesbutkeepingasidessomeof the few wecan dosoby addingfollowing 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 followingline for supporting compression by the browsers especially old browser to compress our data.
  • 32. BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4.0[678] no-gzip BrowserMatch bMSIE !no-gzip !gzip-only-text/html Thistell browsertocompress dataforotherfileincludinghtml aspreviouslybrowserusedtosupport only compressing HTML document. Some of the file that we think need to be compressed are as follows: text/html text/plain text/xml text/x-js text/javascript text/css application/xml application/xhtml+xml application/x-javascript application/javascript application/json 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 maxrequestsperchildinstructsthe apache serverastohow manyrequestsanindividual childprocess will handle. Whatevernumberwe puthere the childprocesswillserve thatmanyrequestsandafter that it stops.Butif we set itto 0 itwill keepacceptingthe requestsanditwill neverexpire. Itisbettertokeep it in 1-3 thousands.
  • 33. MPM module in apache: MPM refers to Multi-processing method. By the help of MPM apache can handle multiple conenctions .Workerand the preforkare the two maintype of MPM inapache. The wayworkeroperatesisit creates extra threads on top of child process to handle each new connections where the prefork MPMcreates newprocessforeachnew connections.One caneasilyswitchbetweenthesetwoandfindoutwhichsooth them best. One of the easiest way to find out which MPMone server is running is by issuing aptitude search apache2-mpm- As we can see in the followingpicture ourserverwe have fourMPMavailable forour serveras indicated by the letter P preceding it. If it was installed it would have I letter preceding it. Fig-20: Available MPM in apache Anotherwayone canfindoutisbyissuing apache2ctl -lgwhichwillshowcompiledmoduleswithinapache server. In our case it will now show any MPMas 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 MPMis been installed as shown in the picture below
  • 34. Fig-21: Installed MPM in apache We now have to enable any of the MPMwe 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 MPMin our server we type in ls /etc/apache2/mods-available/mpm* and we see we have three MPM event, worker, and prefrok available /etc/apache2/mods-available/mpm_event.conf /etc/apache2/mods-available/mpm_event.load /etc/apache2/mods-available/mpm_prefork.conf /etc/apache2/mods-available/mpm_prefork.load /etc/apache2/mods-available/mpm_worker.conf /etc/apache2/mods-available/mpm_worker.load
  • 35. Now if we want to find out the active MPMmodule 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 MPMmodule 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 /etc/apache2/mods-enabled/mpm_prefork.conf
  • 36. We the default configuration is such as follows: <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxRequestWorkers 150 MaxConnectionsPerChild 0 </IfModule> The Startserversindicateshowmanychildprocessthe serverwillinitiate whenitstarts.Here we setit 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.
  • 37. Reducing DNS lookup: The hostname in the lookup directives makes it possible to log in as hostname rather than IP address. Everytime hostnameneedstobe matchedtoIPaddresstheapache serverhastogoforDNSlookupwhich createsextraoverhead.It’srecommendedtokeepthe DNSlookupoff.BydefaultDNSlookupisdisabled. Evenwhenwe wantto use allowanddenywe shoulduse IPaddressinsteadof hostname whichwillstop apache to go for DNS lookup and use up extra processes. Configuring Content Negotiation: Contentnegotiationisthe wayapache servercandeliversthe contenttothe browserthe wayitlikes.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. TypeMaps: To configure TypeMaps in a directory where we want content negotiations we needto create .htaccess file and include the following line AddHandler type-map var In the var extensionwe canuse index.html.varwhichisapache bydefault. We ca explicitlylink with the Variantlike index.html.varorwe can linkto the more defaultindex type bydeclaringall in the directory Index. DirectoryIndex index.html.var index.html index.php MultiViews: InMultiviewsonecanenableitinsidethe .htaccessfilebyaddingfollowinglinetowhicheverthedirectory we want multiviews to be enabled: Options +MultiViews We can setMultiViewsforcontenttype likeservingXhtmlforthe useragentwhosupportitif notitserves 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 qualityso that oldbrowsers will get .html Above configurationinstructsapache tointerpretthe fileaccordingtoitsextensions.Like ifbrowserwants to getindex page fromapache if thebrowsersupportsxhtmlitwill serve theindex.xhtml page ifnotitwill serve the index.html page.
  • 38. We cansetuppreferredlanguagewithMultiViewssothatitcannegotiateautomaticallywiththe 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 andindex.de.html.Whateverthe useragent’sdefaultlanguage 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 serverif workingwithdynamicpagescantake significantamountof memoryanditkeepusingup the memoryuntil itfullyloadsthe dynamiccontents.Itistrue evenforapage withonlyimagesasittreats it like dynamic page and in processallocate lots of memory for work that it does not need that much of memory.Thissignificantlyreducesthe apache performances.If we can set up apache serverto 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 thisbyredirectingstaticpage requeststo lightweightfrontserverandmore intense dynamicpages to back endheavyserver. We canachieve thisbyMod_proxymodulesandrewrite module. For example we cansetuplightweightapache serveronone port80 and heavyweightserveronother port 5500 so that we can redirectstaticpagesand dynamicpagesaccordingly. Thenour configurationfilewill be: ProxyPassReverse / http://%{HTTP_HOST}:5500/ RewriteEngine on RewriteCond %{REQUEST_URI} !.*.(gif|png|jpg)$ RewriteRule ^/(.*) http://%{HTTP_HOST}:8088/$1 [P] Here we are instructingapache thatall the requeststobe sentto the backendserverlisteningonport 5500 exceptthe images. Thenwhenthe backendserverresponse itfirstgoestothe frontendserver and thento the client. Thisway we can isolate dynamicandstaticpage requestsaswell aswe can buildonthisconfiguration and make the heavyrequesttobe forwardedtothe external serveraswell.
  • 39. Unload UnnecessaryModules: Apache serverworksbysetting module wise.Administratorcanchoose setof moduleshe wantsinhis serverandenable it,tweakitthe wayhe wants. Modulesare compilesstaticallyanddynamically. Staticallycompiledmoduleuse lessRAMbutdownside beingaddinganddroppingthe module needs recompilingintoapache whereelsedynamicallyloadedmodulesdoesnotneedcompilingasitcan be loadedbyLoadModule command . Loadingunnecessarymoduleaddsextraloadtothe apache resourcessounloadingunnecessary modulescanimprove the performancesof the apace server. AllowOverride: Allowoverride option indefault/etc/apache2/apche2.conf indirectory isnormallysettonone.If setto none the apache serverlooksfor.htaccessfile ineachdirectoryittraverse.Forexample configuration such as follows: <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory>Makes apache webservertolookforall the .htaccessfile ineachsubsequentdirectories like /var, /var/www,/var/www/html if one requestlike/index.html ismade. Thisadditional lookup slowsdownthe apache server. So it’srecommendedtomake changestoas follows: <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride ALL Require all granted </Directory>So that apache doesnot have to lookfor.htaccessfile ineachdirectory.If there isneed for .htaccessfile inanydirectorymake itenable forthatparticulardirectoryonly. We have to restartapache now to make the .htaccessfile active.
  • 40. How to make user friendly URL in apache: Lot of the time administratorwantstomake URL of website more userfriendly.Forexampleletslookat followingURLof website: http://www.pickaweblamp1.com/index.php?id=712 If we wantusernot to rememberthe trailingpartof the URL we can make it possible inapache with Mod_rewrite module tosomethingsimplerlikebelow: http://www.pickaweblamp1.com/712.html Firstof all we needtoenable rewrite inapache byissuingfollowingcommand sudoa2enmodrewrite Thenwe restart apache server. Once the rewrite module isactivatedwe needtoopenorcreate .htaccessfile inthe directorywe need to applyrewrite module. Thiswillbe validforthe directorythe .htaccessfileresidesaswell asthe subsequesntdirectoriesaswell. With.htaccessfile we canmake changesper directorylevel withoutneedingtoconfigure the main serverconfigurationfile. We thencreate .htaccessfile tothe directorywe wantwithfollowingcommand sudonano /var/www/pickaweb.lamp1/.htaccess Nowwe want to make changestothe sitesforwhichwe are applyingrewrite module to.Sointhe site available directorywe make changestothe default 000-default.conf file if we wantwholesite wise configurationorif we wantper virtual hostwise configurationwe canchange to the virtual host configurationfileinside the site-available directoryinourcase pickaweb.lamp1.conf or pickaweb.lamp2.conf file. We have to make the AllowOverride All inthe directory sectionof eitherthe pickaweb.lamp1.conf or pickaweb.lamp2.conf to enable the .htaccessfile forpickaweb.lamp1orpickaweb.lamp2.conf. If we wantwhole site tobe available forthisrewrite module we needtomake changestothe 000- default.conf file. Nowrestartthe apache servertotake itseffect. So let’ssaywe want http://www.pickaweblamp1.com/index.php?id=712 URL to looklike more userfriendly http://www.pickaweblamp1.com/712.html
  • 41. We needtoadd followingrule in the .htaccessfilethatwe made earlierinside /etc/var/www/pickaweb.lamp1directory Options+FollowSymLinks RewriteEngine On RewriteRule ^id/([a-zA-Z0-9]+)/$index.php?id=$1 Here the the [a-zA-Z0-9] takesanyuppercase of lowercase alphanumericletters. • The asteriskinside the brackets isusedtomatchoccurences. • ([a-zA-Z0-9]+) itwilltake all the alphaalphanumericof 1character • The caret ^ means“start with”,meaningthe URLstarts withthe word “id”. • The dollarsign$ meansthe URL will finishwithslashsign • The $1 meansit will carrywhateverwaswritteninthe groupof bracketsbefore Nowwe save the .htaccessfile andrestartthe apache server. So nowclientsdonothave to memorize the URL as http://www.pickaweblamp1.com/index.php?id=712 Whenthe clienttype inURL as http://www.pickaweblamp1.com/712.html it will requestabove URLin the backendby the apache. More reference onRewrite isavailableat: http://httpd.apache.org/docs/current/mod/mod_rewrite.html Thisare the stepswe can take to optimize our apache serverandmake itfasterand Userfriendlyforthe users.