HOSTING WEBSITE ON LINUX MACHINE PART 2 : CODE AND DEPLOYMENT

Linux fun image

Welcome to the second part of short tutorial of “how to host website on linux machine”. If you haven’t setup basic requirements, you can go through the part one HOSTING WEBSITE ON LOCAL LINUX MACHINE PART 1 : BASIC SETUP AND INTRODUCTION

In this part we shall write a small php website code that would fetch employee details from backend mySQL database. Then, we shall configure it in apache2 webserver.


CODING AND DEPLOYMENT

MySQL

Create sample database and table in mySQL
Database: temp
Table : Employee

Open your terminal and type in commands

mysql -uroot 
create database temp;
CREATE TABLE `Employee` (
  `id` int(11) DEFAULT NULL,
  `name` char(222) DEFAULT NULL,
  `months` int(11) DEFAULT NULL,
  `salary` int(11) DEFAULT NULL
) ;

Populate some entries

insert into Employee(id, name, months, salary) values(1,'Savan', 12, 300);
insert into Employee(id, name, months, salary) values(2,'John', 13, 353);
insert into Employee(id, name, months, salary) values(3,'maria', 13, 223);
insert into Employee(id, name, months, salary) values(4,'Vivek', 34, 321);
create and populate mysql database and table image

Hosting under Apache2

Before doing any kind of changes let’s understand the basic directory structure of apache2. The default directory for apache2 is at /etc/apache2

cd /etc/apache2
ls -F

Output

apache2.conf  envvars     magic            mods-enabled/  sites-available/
conf.d/       httpd.conf  mods-available/  ports.conf     sites-enabled/
Apache directory structure
  • apache2.confmain configuration file for apache2 server.
  • ports.conThis file is used to specify the ports that virtual hosts should listen on. Be sure to check that this file is correct if you are configuring SSL.
  • conf.d/This directory is used for controlling specific aspects of the Apache configuration. For example, it is often used to define SSL configuration and default security choices.
  • sites-available/This directory contains all of the virtual host files that define different web sites. These will establish which content gets served for which requests. These are available configurations, not active configurations.
  • sites-enabled/ This directory establishes which virtual host definitions are actually being used. Usually, this directory consists of symbolic links to files defined in the "sites-available" directory.
  • mods-[enabled,available]/ These directories are similar in function to the sites directories, but they define modules that can be optionally loaded instead.

To easily manage, we shall create separate space for website.

Make Website Folder

Open teminal and follow commands

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

public_html will hold all the website code.

Write website code

Make a new file index.php inside /var/www/sampleexample.com/public_html Open editor of your choice and copy the php code given below.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Website hosting example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Employee Info</h2>
  <p>List of employees in database</p>
  <table class="table">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Salary</th>
      </tr>
    </thead>
    <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "temp";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, name, salary FROM Employee";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["id"]. "</td><td>" . $row["name"]. "</td><td> " . $row["salary"]. "</td></tr><br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>
  </table>
</div>

</body>
</html>
Now the website code is ready, we need configure apache.


Change user permissions

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

$USER will take value of logged in user.

Also change the permission of the file

sudo chmod -R 755 /var/www

Configure Apache config file

Navigate to folder /etc/apache2/sites-available/ By default, it contains the default config file 000-default.conf Copy that file with name of our site.

sudo /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/sampleexample.com.conf

Open sampleexample.com.conf
The content of file would look like

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

We need to change DocumentRoot and add two more parameters.Change document root to

DocumentRoot /var/www/sampleexample.com
ServerName sampleexample.com
ServerAlias www.sampleexample.com

Enable New Virtual Host

Apache2 comes with the bundle of software. a2ensite is one among them to enable the site.

sudo a2ensite sampleexample.com.conf

Now you need to restart the apache2 webserver

sudo service apache2 restart

Optional[Set up local host file if practicing locally]

Open /etc/hosts to add entry of biinding of address.

sudo vi /etc/hosts

Bind local ip 127.0.0.1 with sampleexample.com site
Add entry

127.0.0.1       sampleexample.com

NOTE: these are tab separated values.


apache /etc/hosts file image.

Check your setup

Open web-browser and navigate to
http://sampleexample.com

NOTE: In case it fails,


  1. cd /etc/apache2/sites-available
  2. mv 000-default.conf /tmp
  3. sudo service apache2 restart (it will fail)
  4. mv /tmp/000-default.conf /etc/apache2/sites-available/
  5. sudo service apache2 restart

Now it should work. And you will see following result


Apache hosting sample website test image

Conclusion

Well that’s it, with this now you are capable of hosting website on linux machine. There is no software limit on the number of domain names Apache can handle. You can create as many servers as you want. This ends the tutorials series. If you face any issues, or have any suggestions do leave comment in section below.
That's all for now. Do leave suggestions, comments or questions in the comment section below. If you liked the tutorial, share with your friends and spread the word.