Tuesday, 10 April 2018

How to install and configure NGINX on CentOS 6


So you’ve just gotten your new self-managed server. Congratulations on a wise decision! As a savvy web professional, you likely already know some of the advantages of the NGINX web server as opposed to the traditional Apache configuration. This article will help you replace Apache and install and configure NGINX on a new server. It assumes a certain level of previous server administration knowledge, or at least a willingness to learn. If you’re ready to grab the bull by the horns and deploy a web stack using NGINX, you can use the article as a first step to building common web stacks such as Node.js, LEMP, and popular web frameworks such as Django.
Note: This article is not meant to serve as a guide for migrating existing sites on a production server from Apache to NGINX. Please keep that in mind when following the steps below, as one of the steps we’ll take is turning Apache off. Doing so on a server with live production sites will bring sites down until they are reconfigured for NGINX.

What is NGINX?

NGINX (pronounced Engine ex) was released for production in 2004 and is rapidly becoming a popular alternative to the traditional Apache web server suite. It features an event-driven design, which can make better use of today’s computer hardware than Apache’s process-driven design. Because of this, NGINX is often seen as the “faster” alternative to Apache, being able to handle a higher load of concurrent connections while using less resources. There are many comparisons out there between Apache and NGINX; we’ll leave the debate up to the community. But here are a few pointers that outline the key reasons to choose Apache versus NGINX. At the end of the day, the choice of the web server platform is entirely dependent on what you’re doing with the server.

NGINX vs. Apache

If you are …
  • Using the server to host a single website with high traffic
  • Comfortable with doing advanced configuration and tweaking, and have the skillset to do so
  • Wanting to go with newer frameworks, such as Node.js, Python/Django
  • Wanting to use an alternate to CGI/FastCGI, such as WSGI
  • Are OK with less add-ons, components, or modules
  • Are OK with a more complex configuration
… then NGINX might be a good fit for you.
If you are …
  • Using traditional MySQL/PHP applications, such as WordPress or Drupal
  • Planning to host many websites with different configurations per site through an .htaccess
  • Are more comfortable with a platform that is very well known and documented
  • Want access to a variety of different modules, add-ons, and components
  • Want your web server to work right out of the box
… then you probably want to stick with Apache.
Here’s a good rule of thumb: If you want to run ONE site at lightning speed on an advanced configuration, NGINX is probably the server for you. If you want to run MANY sites with easy configuration and flexibility, Apache is still your bread and butter.
At the end of the day, both are a good fit for most sites. Apache is included with all major Linux distributions and requires much less configuration. However, most benchmarks have clocked NGINX at serving websites faster. You can also see some configurations that run both — it’s all up to you as the admin.

Pre-flight check

Before we begin, let’s make sure we have everything we need.In order to perform this task, you’ll need an active CentOS 7 server, as well as an SSH client such as PuTTY (for Windows) or Terminal (Mac). We recommend a GoDaddy VPS if you’re just getting started, or a full dedicated server if you’re ready to take total control.
A domain. We will, of course, need to tie a domain to your NGINX web server, so we’ll need a domain to use. All of our examples will use the domain nginxsite.com. When going through the article, replace any instance of nginxsite.com with the domain you want to use for your site.
Make sure you can connect to the server through SSH. You can find instructions here. If this is step is a challenge, then I’ll level with you — this article might not be for you.
A browser window open to your search engine of choice. Unlike Apache, NGINX has a lot of custom tinkering that you might need to do according to your needs as webmaster, and other variables that this article not account for. But this shouldn’t phase you — you’re a sysadmin, and search engines are your ally.
If all of these elements are in place, we’re ready for take-off. Let’s set up NGINX.

Installing NGINX on CentOS 6

Every major Linux distribution comes packaged with Apache by default; it’s literally integrated into the OS by now (similar to how Windows comes packaged with IIS natively). However, since we’re setting up a dedicated space for NGINX, it’s possible that the existing Apache configuration can cause problems when NGINX is put in its place. What we’re going to do is turn Apache off, then configure Apache so that it does not start upon server reboot.
Turning Apache off on a server with live sites will bring those sites down; act accordingly.

1. Log into your server via SSH, then get to the root user by running:

sudo su -
Note: We’ll remain as the root user for the remainder of the article.

2. Shut Apache down. This will bring down any current websites that are hosted on the server.

service httpd stop

3. Now we need to remove Apache from the boot cycle, so that it doesn’t try to start up during server boot.

chkconfig httpd off
Apache is now fully shut down, and won’t be starting up again until we say so.
Note: If you have buyer’s remorse later on about NGINX, and want Apache to start on boot again, you can easily correct this previous command by running:
chkconfig httpd on
Now that Apache is riding off into the sunset, we can start to install NGINX.

4. Add the EPEL-Release yum repository, which will have NGINX for us:

yum install epel-release

5. Now that our repository is installed on the server, we can use yum to install NGINX:

yum -y install nginx

6. Start NGINX:

service nginx start

7. Then configure the server to start NGINX upon reboot:

chkconfig nginx on
You should now be able to see an NGINX test page by going to http://1.2.3.4, using your IP address for your server.

Configuring NGINX to serve for your domain

Alrighty, we’ve switched from the Apache schooner to the NGINX steamboat. Now it’s time to get it working for your domain.

Create a new user for the webspace

Before doing anything, we need to create a UNIX user for your webspace.

1. Type the following command to create your user:

useradd
To demonstrate, I’ll add my user nginxsite:
useradd nginxsite

2. Give this user a password with the following:

passwd
//for our example
passwd nginxsite

3. Set the password for this user.

Your characters won’t register in the terminal when you type. That’s fine; it’s just Linux protecting you by not logging the password entry. Follow safe password practices.
Your user should now be properly set up.

Create a new directory for the site DocumentRoot

Next, we need to create the directory that will act as the DocumentRoot for this website. It’s a good idea to follow a standard naming convention if you’r hosting multiple websites.

1. Follow the standard naming convention used by cPanel, and make the DocumentRoot based on the name public_html, like so:

mkdir -p /var/www/nginxsite.com/public_html

2. Create a test index.html in this directory so that we have something to look at when we test the configuration later:

vim /var/www/nginxsite.com/public_html/index.html

3. Use the HTML below the fold for this test index file:

www.nginxsite.com

Success! Nginx is properly serving on this domain!


4. Give ownership of that directory to the user in question:

chown -R nginxsite:nginxsite /var/www/nginxsite.com/public_html

5. Set permissions for this folder so that it can be viewed by the outside world:

chmod 755 /var/www/nginxsite.com/public_html
Our directory is now set up, and we have a test index.html file to use.

Configure NGINX to recognize new VirtualHosts (server blocks)

Now for the fun part. Configuring a VirtualHost for NGINX is very similar to Apache, though the layout of the configuration file is a bit different. Also, in NGINX, they are referred to as “server blocks,” and not the Apache VirtualHost label. It’s worth noting that when editing an Apache configuration file, we’re editing XML. With NGINX, we’re actually editing the C code.

1. Set up directories where the server blocks will live:

mkdir /etc/nginx/sites-available
mkdir /etc/nginx/sites-enabled
Note: In theory, instead of doing this by having a directory tree, you could simply edit the global configuration file. However, setting up a directory tree (which is what Debian-based Linux distros, such as Ubuntu, do), allows for an easier configuration down the line as more website are added.

2. Open the global NGINX configuration file in the text editor of your choice (we will use vim):

vim /etc/nginx/nginx.conf

3. Add these lines to the end of the http {} block, then save the file:

include /etc/nginx/sites-enabled/*.conf;
server_names_hash_bucket_size 64;
Great. Now NGINX can recognize the server block.

Configure the actual NGINX server blocks

1. Create a new file specifically for the server block for your site. (The line below will do this and open it in vim.)

vim /etc/nginx/sites-available/nginxsite.com.conf

2. Paste a new NGINX server block in here, which should look like this:

server {
listen       80;
server_name  nginxsite.com www.nginxsite.com;
location / {
root   /var/www/nginxsite.com/public_html;
index  index.html index.htm;
try_files $uri $uri/ =404;
}    error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}
}
Let’s break down a few important parts of this process:
server_name. This is the domain you’ll be using for your site. Instead of localhost, we will use the public facing domain and www version of the domain you want to use, like so:
server_name  nginxsite.com www.nginxsite.com;
root. This should be set to the directory where the files live. In our example this can be changed to /var/www/nginxsite.com/public_html:
root /var/www/nginxsite.com/public_html;
try_files. This is something we need to add in the location block. What we are doing here is telling the server to display a 404 error when a given file is not found. So you’ll place this right under the index definition, before the closing } bracket:
try_files $uri $uri/ =404;
Create your server block using these parameters, then go ahead and save and close the file.

3. Create a symbolic link between sites-available and sites-enabled:

ln -s /etc/nginx/sites-available/nginxsite.com.conf /etc/nginx/sites-enabled/nginxsite.com.conf

4. Restart NGINX:

service nginx restart
You’re done! Provided your DNS and/or hosts file is pointed for your domain, you should now be able to go to the domain in a web browser and see the test HTML page we created earlier.

Apache vs Nginx: Selection of a Perfect Web Server

Introduction of Apache

Apache is said to be the leading HTTP server software available on the web. It was initially developed and released as an open source of installation and configuration patches for NCSA HTTPD process in the year 1995. It has been rewritten from the ground up for two times since its development. It is of high industry standard and most of the web servers run on apache. It is backend software which runs more than 60% of all websites out there and even for the web development and localhost projects it stands on top.

Advantages of Apache

  • It is open source software written by novice for the fun of solving problems. the major benefit of this open source development model is that many people are contributing to the source code of Apache, which means that bugs will get fixed quicker and constantly. New services in the open source software will be slower in coming when compared to internet information server. This is because there is not a marketing department which tries to find new things through which sales will be drawn. So, it is ensured that Apache which runs on unix or linux is stable, robust and secure.
  • Apache as an open source software is distributed under license conditions which make the source code available for free. So, it is quite possible for everyone to download the apache server module and run it under windows even without paying any license fee. This is extremely crucial for web hosting companies as well as internet service providers who have to constantly increase the capacity of the server.

Disadvantages of Apache Server

Most of the apache installations go off without a hiccup or hitch whereas most of the linux distributions bundle apache as a part of their installation process. they also have apache in already pre-configured and ready to run status. However, if you go tend to face any problem in the configuration, there is no central office to get technical support. Only forums on the web is available with full of people who faced the same problem and documented the solutions that they have obtained to them. The consequence of this is that if in cause you have anything to fix, you must be comfortable with command line prompts and the cryptic unix command sets as there is no setup wizards or handholding for beginners.

Introduction of NGINX

Nginx is said to be an open source reverse proxy service confined for HTTPS, HTTP, POP3, SMTP and IMAP products and also as a HTTP cache, load balancer, and a web server. The Nginx project commenced with a powerful focus on high performance, low memory usage and high concurrency. Overall, Nginx leaves very small footprint of processing data on your web server. It runs perfectly on BSD variants, Max OS X, Linux, AIX, Solaris, HP UX and on other *nix flavors. It also includes a proof of concept port, especially for Microsoft windows. Nginx can be used to service dynamic HHTP content using SCGI handlers for scripts, fastCGI, Phyusion passenger module or WSGI application servers and also as a software load balancer.

Advantages of NGINX
  • Nginx can load balance connections to the application server and can even choose appropriate endpoints for reducing latency. It also provides more control over failure processes in which failing background machines can be removed out of rotation seamlessly.
  • Nginx helps in improving the performance in handling static content. This helps in keeping off the unnecessary traffic of the application server.
  • Server management can also be simplified with distinct layers for application servers and web servers. The application server can be taken down for maintenance sans affecting normal HTTP traffic.

Disadvantages of NGINX

Nginx provides a hard time, when it comes to creating modules. Hence, the developer has to find the function required to create the module with the internal code of Nginx web server.

Apache vs Nginx: Which Has What?

Apache is a well established and flexible web server and is used by a huge number of customers all over the world for delivering static and dynamic content. Apache efficiently runs on a wide range of Oss and is properly maintained. The ubiquity of apache indicates that a considerable amount of user generated documentation is available.
Nginx is designed to be fast at serving the static web pages. If a site is obtaining a huge amount of concurrent hits which are seeking static pages, then nginx design has advantages over other servers.
Apache comes with the ability of being customized. It includes a set of rich features which can be extended and modified by using readily available addon modules to suit any different business and technical needs.
As nginx is newer, it requires less support and documentation when compared to well-established web servers. Its lightweight design means that it can be extremely difficult to customize which is necessary for complex and large configuration.
As apache makes use of primary process based processing model, it tends to consume more memory under high server loads. This would result in degraded performance, even after the launch of Apache 2.4 recently, which promised improvements in caching and speed.
Nginx can be regarded as a newer rival to apache and is designed to be lightweight and simple and to obtain a few hardware resources than most other web servers. Nginx accomplish this by using event based processing model that requires less memory when compared to a process based server uses.

Conclusion

Both Apache and Nginx are perfect solutions while they have both advantages as well as disadvantages. Depending on the technical requirements and needs of your business, you can choose the one which might be right for you. For new users NGINX is a better option.

What is Nginx? How Nginx Works? Explained

NGINX (Pronounced as Engine-X) is an open source, lightweight, high-performance web server or proxy server. Nginx used as reverse proxy server for HTTP, HTTPS, SMTP, IMAP, POP3 protocols, on the other hand, it is also used for servers load balancing and HTTP Cache. Nginx accelerates content and application delivery, improves security, facilitates availability and scalability for the busiest websites on the Internet.
NGINX
In easy term, Nginx is just a kind of software which is used in web servers to serve the concurrent requests. Previously we used to install Apache in web servers to handle these functions; but as the world is growing and demanding more things at one time the term concurrency comes into the picture and Nginx launched for the same thing.

Why Apache is Slow? How Nginx Came in Action?

Apache introduced in 1995; when there was no concept multitasking. Later when the need of multitasking required then MPM (Multi-Processing Module) was added in Apache to overcome this issue. But with this new feature memory consumption starts increasing with the coming years; where giant sites like Google and Facebook getting millions of hits every day. So the need of new platform or change in Apache was required.
This issue was named as C10K (Concurrent 10 Thousand) Problem.
Then Igor Sysoev started the development of Nginx in 2002 to overcome the same issue, and the first time Nginx was publicly released in 2004.

Now (in 2014) Nginx hosts nearly over 12% (22+ Million) of active sites across all domains.

How Does Nginx Work?

Nginx follows event-based process; it does not create individual thread of request for each process like Apache does, but smartly follows events of a process. Below is the demonstration of a Nginx server handling concurrent MP3 and MP4 file requests.
How NGINX Works? - Demonstration
How Does NGINX Work? – Demonstration
Nginx divided its job into Worker Connections and Worker Process. Here worker connections are managing the request made and the response obtained by users on the web server; in the same time these request are passed to its parent process which is Worker Process.
A single worker connection (See in Diagram: Worker Connections) can handle around 1024 connections at a time. It is the greatest ability of a worker connection.
There can “n” numbers of the worker process in Nginx based on the type of server you have and each worker process handle different jobs so that it can handle more numbers of concurrent requests.
Finally, the worker process transfers the requests to Nginx Master Process which quickly responds to the unique requests only.

Nginx is Asynchronous; that means each request in Nginx can be executed concurrently without blocking each other like a water pipe. So this way Nginx enhances the virtually shared resources without being dedicated and blocked to one connection.
That is why Nginx is able to do the same work with less amount of memory and utilizes that memory in an optimized way.

What is Apache?

Install and Download Apache

What is Apache?

Apache is a remarkable piece of application software.  It is the most widely used Web Server application in the world with more than 50% share in the commercial web server market. Apache is the most widely used Web Server application in Unix-like operating systems but can be used on almost all platforms such as Windows, OS X, OS/2, etc. The word, Apache, has been taken from the name of the Native American tribe ‘Apache’, famous for its skills in warfare and strategy making.
It is a modular, process-based web server application that creates a new thread with each simultaneous connection. It supports a number of features; many of them are compiled as separate modules and extend its core functionality, and can provide everything from server side programming language support to authentication mechanism. Virtual hosting is one such feature that allows a single Apache Web Server to serve a number of different websites.
Apache Tutorials for Beginners

How to install Apache

There are numerous ways of installing the package or application.  There are enlisted below -
  1. One of the features of this open source web application is that anyone can make installer as per their own environment. This has allowed various vendors like Debian, Red Hat, FreeBSD, Suse etc. to customize the file location and configuration of apache taking into account other installed applications and base OS.
  2. Apart from installing it from a vendor based installer, there is always the option of building and installing it from the source code. Installing Apache from source file is a platform independent & works for all OS.
The apache web server is a modular application where the administrator can choose the required functionality and install different modules as per his/her requirement.
All modules can be compiled as a Dynamic Shared Objects (DSO is an object file that could be shared by multiple apps while they are executing) that exists separately from the main apache file.  The DSO approach is highly recommended, it makes the task of adding/removing/updating modules from the servers configuration very simple.

Install Apache:Linux Platform

On Red Hat or rpm based systems
If you are using an rpm (RedHat Package Manager is a utility for installing application on Linux systems) based Linux distribution i.e. Red Hat, Fedora, CentOs, Suse, you can install this application by either vendor specific Package Manager or directly building the rpm file from the available source tarball.
You can install Apache via the default Package Manager available on all Red Hat based distributions like CentOs, Red Hat and Fedora.
[root@amsterdam ~]# yum install httpd
The apache source tarball could be converted into an rpm file using the following command.
[root@amsterdam ~]# rpmbuild -tb httpd-2.4.x.tar.bz2
It is mandatory to have -devel package installed on your server for creating .rpm file from source.
Once you convert the source file into an rpm installer, you could use the following command to install Apache.
[root@amsterdam ~]# rpm –ivh httpd-2.4.4-3.1.x86_64.rpm
After the installation the server does not start automatically, in order to start the service, you have to use any of the following command on Fedora, CentOs or Red Hat.
[root@amsterdam ~]# /usr/sbin/apachectl start

[root@amsterdam ~]# service httpd start

[root@amsterdam ~]# /etc/init.d/httpd start

Install Apache from Source

Installing apache from the source require the –devel package to be installed on your server. .You can find the latest available version of Apache, you can download it here .  Once you download the source file move it to the /usr/local/src folder.
[root@amserversterdam ~] cd /usr/local/src

[root@amserversterdam ~] gzip -d httpd-2.2.26.tar.gz

[root@amserversterdam ~] tar xvf httpd-2.2.26.tar

[root@amserversterdam ~] httpd-2.2.26
In order to see all configuration option available for Apache, you can use ./configure –help option.  The most common configuration option is –prefix={install directory name}.
[root@amserversterdam ~]./configure --help

[root@amserversterdam ~]./configure –prefix=/usr/local/apache –enable-so

[root@amserversterdam ~] make

[root@amserversterdam ~] make install
The above example shows the compilation of Apache within the /usr/local/apache directory with the DSO capability. The –enable-so option, can load required modules to apache at run time via the DSO mechanism rather than requiring a recompilation.
Once the installation completes, you can browse the web servers default page with your favorite browser.  If firewall is enabled on your server, you must have to make exception for port 80 on your OS firewall.  You can use the following command to open port 80.
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
service iptables save
You can see the default Apache2 Welcome screen by browsing your server IP address.

Apache Tutorials for Beginners

Learn about Apache Virtual Host in 10 minutes

What is Virtual Host?

An Apache web server can host multiple websites on the SAME server. You do not need separate server machine and apache software for each website. This can achieved using the concept of Virtual Host or VHost.
Any domain that you want to host on your web server will have a separate entry in apache configuration file.
Apache Tutorials for Beginners

Types of Apache Virtualhost

  1. Name-based Virtual host
  2. Address-based or IP based virtual host and.

Name-based Virtual Host

Name based virtual hosting is used to host multiple virtual sites on a single IP address. 
Apache Tutorials for Beginners
In order to configure name based virtual hosting, you have to set the IP address on which you are going to receive the Apache requests for all the desired websites.  You can do this by NameVirutalHost directive within the apache configuration i.e. httpd.conf/apache2.conf file.

Apache virtual host Example:

NameVirtualHost *:80

<VirtualHost 192.168.0.108:80>

ServerAdmin webmaster@example1.com

DocumentRoot /var/www/html/example1.com      

ServerName www.example1.com

</VirtualHost>

<VirtualHost 192.168.0.108:80>

ServerAdmin admin@example2.com

DocumentRoot /var/www/html/example2.com

ServerName www.example2.com

</VirtualHost>
You can add as many virtual hosts, as per your requirement. You can check your web configuration files with:
[root@amsterdam ~]#httpd –t
Syntax OK
If the configuration file has some wrong syntax, it will throw an error
[root@115 conf.d]# httpd -t

Syntax error on line 978 of /etc/httpd/conf/httpd.conf:

Invalid command '*', perhaps misspelled or defined by a module not included in the server configuration

IP-based Virtual host

In order to setup IP based virtual hosting, you need more than one IP address configured on your server.  So, the number of vhost apache will depend onnumber of IP address configured on your server.  If your server has 10 IP addresses, you can create 10 IP based virtual hosts.
Apache Tutorials for Beginners


In the above diagram two websites example1.com and example2.com were assigned different IPs and are using IP-based virtual hosting.
Listen 192.168.0.100:80

<VirtualHost 192.168.10.108:80>

ServerAdmin webmaster@example1.com

DocumentRoot /var/www/html/example1.com      

ServerName www.example1.com

</VirtualHost>

<VirtualHost 192.168.10.109:80>

ServerAdmin admin@example2.com

DocumentRoot /var/www/html/example2.com

ServerName www.example2.com

</VirtualHost>

How to Run PHP/Ruby with Apache?

What Apache needs to Run Php File?

Running Php files on Apache needs mod_php enabled on your server.  It allows Apache to interpret .Php files.  It has Php handlers that interpret the Php code in apache and send HTML to your web server.
 If mod_php is enabled on your server, you will have a file named php.conf in /etc/httpd/conf.d/ directory.  You can also check it with: 
httpd -M | grep "php5_module"
The output will be similar to:
Apache Tutorials for Beginners

Php handlers in Apache

  • mod_php
  • CGI
  • FastCGI
  • suPHP
mod_phpis the oldest PHP handler, it makes PHP part of apache and does not call any external PHP process. This module is installed by default in every Linux distribution repository, so enabling/disabling this module is very easy.
If you are using FastCGI as your PHP handler, you can set multiple versions of PHP to be used by different accounts on your server.
FastCGI i.e. mod_fastcgi is an extension of mod_fcgid, where as mod_fcgid is a high performance alternative of CGI i.e. mod_cgi . It starts sufficient number of instances of CGI to handle concurrent web requests.  It also uses suexec to support different users with their own instances of PHP and improves web security. 
Running ruby files on Apache needs mod_ruby to be enabled.  Apache can also handle ruby files through FastCGI.  It is possible to use multiple version of ruby with the help of mod_fcgid i.e. FastCGI.
You can also install apache passenger and configure Apache to use it for serving ruby pages.
(Phusion Passenger also known as “passenger” is a free web server module that is designed to integrate with Apache and Nginx )
Steps to install mod_ruby on your server -
cd /tmp

wget http://www.modruby.net/archive/mod_ruby-1.2.6.tar.gz

tar zxvf mod_ruby-1.2.6.tar.gz

cd mod_ruby-1.2.6/                    

./configure.rb --with-apr-includes=/usr/include/apr-1

make

make install

How to run Ruby with Apache

We have to add the mod_ruby module to the Apache configuration i.e. /etc/httpd/conf.d/ruby.conf and add the following line.
LoadModule ruby_module modules/mod_ruby.so
If you like to enable or disable these modules, you have to edit the apache configuration file and comment or uncomment these modules, if the web server is already compiled with these modules.
Apache Tutorials for Beginners

How to Secure Apache Web Server

Securing your web server is very important, it means allowing others to see only the intended information & protecting your data and restricting access.
These are common things that enhance your Apache web servers’ security.

1) Hiding Apache version and OS information:

Apache displays its version and the name of the operating system in errors as shown in below screenshot.
Apache Tutorials for Beginners
A hacker can use this information to launch an attack using the publicly available vulnerabilities in the particular version of the server or OS.
In order to prevent Apache webserverfromdisplaying this information, we have to modify
“server signature” option available in the apache configuration file.  By default, it is “on”, we need to set it “off”. 
vim /etc/httpd/conf/httpd.conf
ServerSignature Off

ServerTokens Prod
We have also set “ServerTokens Prod” that tells the web server to return only apache and suppress the OS major and minor version
After modifying the configuration file, you have to restart/reload your apache web server to make it effective.
service httpd restart
Apache Tutorials for Beginners

2) Disable Directory Listing

If your document root directory does not have an index file, by default your apache web server will show all the content of the document root directory.
Apache Tutorials for Beginners
This feature could be turn off for a specific directory through “options directive” available in the Apache configuration file.
<Directory /var/www/html>

    Options -Indexes

</Directory>
Apache Tutorials for Beginners

3) Disabling unnecessary modules

It is good practice to disable all unnecessary modules that are not in use.  You can see list of enabled module available in your apache configuration file -
[root@amsterdam ~]#httpd –M

perl_module (shared)

php5_module (shared)

proxy_ajp_module (shared)

python_module (shared)

ssl_module (shared)
Many of the listed modules can be disabled likemod_imap, mod_include, mod_info, mod_userdir, mod_autoindex, as they are hardly used by any production web servers.
vi /etc/httpd/conf/httpd.conf

#LoadModule auth_digest_module modules/mod_auth_digest.so
Once you commented the module, save the file.
Restart apache services with following command.
/etc/init.d/httpd restart

4) Restricting Access to files outside the web root directory

If you like to make sure that files that is outside the web root directory are not accessible, you have to make sure that the directory is restricted with “Allow” and “Deny option” in your web server configuration file.
<Directory/>

Options None

AllowOverride None

Order deny,allow

Deny from all

</Directory>
Once you restrict acess outside the web root directoy, you will not be able to access any file located on any other folder on your web server, you will get 404 return code.
Apache Tutorials for Beginners

5) Using mod_evasive to rebutting the DoS attack

If you like to protect your web server from Dos (i.e. Denial of Service) you must enable the module mod_evasive.  It is a third party module that detects Dos attack and prevents the attack from doing as much damage as it would do if left to run its course. It could be downloaded here.

6) Using mod_security to enhance apache security

This module works as a firewall for Apache and allows you to monitor traffic in real time.  It also prevents the web server from brute force attacks. The mod_security module could be installed with the default package manager of your distribution.
Apache Tutorials for Beginners

7) Limiting request size

Apache does not have any restriction on the total size of the http request that could lead to a DoS attack.  You can limit the request size of an Apache directive “LimitRequestBody” with the directory tag. The value could be set anything from 0 to 2 GB (i.e. 2147483647 bytes) as per your requirement.
<Directory "/var/www/html/uploads">

   LimitRequestBody 512000

</Directory>

Apache Log Format

Apache logs provide detailed information that help to detect common issues with server.
In order create access logs, mod_log_configmodule must be enabled.

Three directives available in apache config file i.e.

  • TransferLog: Creating a log file.
  • LogFormat : Specifying a custom format.
  • CustomLog : Creating and formatting a log file.
TransferLog directive is available in the apache configuration file and it rotates virtual host log files as per set parameters.
<VirtualHost www.example.com>

  ServerAdmin webmaster@example.com

  DocumentRoot /usr/www/example/httpd/htdocs/

  ServerName www.example.com

  ServerAlias example.com www.example

  ErrorLog /usr/www/example/httpd/logs/error_log

  TransferLog/usr/www/example/httpd/logs/accesslog

  CustomLog /usr/www/example/httpd/logs/accesslog combined

</VirtualHost>

Two types of Apache Log Format

  • Common Log Format
  • Combined Log Format.
You can enable them by editing the apache configuration file i.e. apache2.conf (Debian/ubuntu) or httpd.conf (rpm based systems) file

Common Log Format

LogFormat "%h %l %u %t \"%r\" %>s %b" common

CustomLog logs/access_log common
Common Log generated by Apache
[Wed Oct 11 14:32:52 2000] [error] [client 127.0.0.1] client denied by server configuration: /export/home/live/ap/htdocs/test

Combined Log Format

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

CustomLog log/access_log combined
Here,
  • %h is the remote host
  • %l is the identity of the user determined by identd
  • %u is the user name determined by HTTP authentication
  • %t is the time the server finished processing the request.
  • %r is the request line from the client. ("GET / HTTP/1.0")
  • %>s is the status code sent from the server to the client (500, 404 etc.)
  • %b is the size of the response to the client (in bytes)
  • Referer is the page that linked to this URL.
  • User-agent is the browser identification string.
Combined Log generated by Apache:
199.187.122.91 - - [06/Mar/2014:04:22:58 +0100] "GET /robots.txt HTTP/1.1" 404 1228 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)"
Custom Log creates separate log file for each Virtual Host on your server.  It needs to be specified in the virtual host section of the config file.
You can see below mentioned virtual host configuration, generated log will be custom for that virtual host and the format will be combined.
Apache Tutorials for Beginners

Configure your very first Production Web Sever

1.  In order to have a running production web server, you need a dedicated node (Physical/Virtual or cloud instance) running Linux/Unix, Windows, MacOS etc. 
2.  The Web Server must have a direct network connection and a staticIP address configured on it.
3.  It needs to have all the modules required for running web pages.  If a web server processes PHP pages, it needs to have PHP  module enabled.
Apache Tutorials for Beginners
  1. It also needs to have a good Antivirus application configured and running for securing the Web Server from Malware or Virus attacks.  You also need mechanism to update the configured antivirus/anti malware application on regular basis without any manual intervention in order to get maximum benefit from them.
  2. If you have hundreds of domains to be hosted on your web server, you must have to implement limitations on file system quota for each domain, number of databases each domain can create, number of email accounts per domain etc.
  3. If your web server has been setup for shared hosting services, users on your web server needs to be restricted. A shared hosting  user should have least user privilege so that he does not damage important files & break the entire server. Apache does not provide any such functionality and needs different third party applications, customization of OS to achieve this. 
  4. If you are adding a new domain on your web server, it needs editing hundreds of configuration file to enable all features for the added domain.
  5. If one of the hosted domains requires different PHP setting than rest of the domains, implementing this in core Apache web server is very complex and needs customization of your web server in great extent.
  6. A production web server needs a firewall to block unwanted traffic that could cause high load on your server.  Implementing IPTABLE rules with command line is very complex.  It needs expertise of core Linux/Unix environment to write effective firewall rules for blocking unwanted traffic.  IPTABLE is based on netfilter module; it is an OS level firewall that allows an administrator to create rules for incoming/outgoing traffic on the server.
  7. A production web server requires several different applications like EmailFTP for file upload, Domain Name System for parked domains.  Managing all these applications on a core Linux/Unix system requires expertise on the respective technologies.
So, one can say that managing a web server for multiple domains is very complex task and requires editing hundreds of configuration file, customizing each application to fulfill the desired result.  Troubleshooting any miss configuration will be very difficult for beginners.

The Solution using Cpanel or similar software

Cpanel provide a graphical way of managing your web server.  It is meant to provide mass hosting services that is easy to use and configure.  cPanel has reduced the technical barriers to entry into the hosting and web server management.  It makes complex task easier, it provides many useful and easy to use web interfaces that perform common system administration tasks required to operate a web server.
Apache Tutorials for Beginners
cPanel compiles its own version of software.
 If you have to recompile your web server i.e. apache on normal Linux platform, you have to manually select/search the module that is required.  cPanel provides Easyapache functionality that is a script based web server compilation method.
Apache Tutorials for Beginners
 It not only provides you web services but also Mail, DNS, FTP and many more services that is required for your web application.
A task that needs expertise on core Linux/Unix based hosting like installing SSLs, recompiling Apache with different PHP modules, updating Web Security, configuring effective IPTABLE rules, Adding ftp users, creating mail accounts for each domain, scanning your document root with antivirus and creating databases are easy to complete with cPanel.
It provides a lot of scripts that fixes, install and troubleshoot common administrative tasks.
It provides a backup and restore functionality eliminating the need to manually copy files to backup storage.  If you are backing up your domain, cPanel will create a tar file that will contain document root folder, email accounts and mails, ftp accounts, databases, DNS records and other applications.
It also provides a robust documentation, andhas a very big community of users where you could discuss and get solution of your issues.
So, one can say that cPanel is a best application for managing your web server with required features.  It provides you, easy to use interface for managing your domain and a mechanism to avoid complexity of managing core Web Server.


There are many competing products to cPanel like Plesk, ISPConfig, Ajenti, Kloxo, Open Panel, Zpanel etc.