How To Install Laravel on Ubuntu 16.04 VPS

How To Install Laravel on Ubuntu 16.04 VPS

With this tutorial, you will start from a clean Ubuntu 16.04 install, set it up to run Laravel, and end up with a demo Laravel application installed. Other articles in this series will show you how to set up the database and Laravel environment, and then how to strenghten the Laravel setup for production.

;

What we are going to cover

  • installation of Apache and PHP 7.2,
  • creation of user which will have access to the app,
  • installation of Laravel itself,
  • setting up Apache to execute the app.

PRE-REQUISITES

We shall install and deploy Laravel 5 on Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access

Step 1: Creating a Non Root User

Once you are logged in as root, you can create a new user account that you’ll use to access the app once it is installed. We’ll call the new user laraveluser. To create it, run:

adduser laraveluser

Then, add it to the sudo group, so that you can run commands as sudo:

usermod -aG sudo laraveluser

Step 2: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://SERVER_IP/. If that does not work, try adding :80 in the end, like this:

http://SERVER_IP:80

You should see a welcome page for Apache, which means that you now have Apache running.

Step 3: Install PHP 7.2

We are installing version 5.8 of Laravel, which requires a version of PHP greater than 7.1.3. We shall install PHP 7.2. First install the prerequisite packages:

sudo apt-get install software-properties-common python-software-properties

Then, add the ondrej PPA:

sudo add-apt-repository -y ppa:ondrej/php
sudo apt-get update

and update your sources by running:

sudo apt install php -y

Install PHP 7.2 using the following command:

sudo apt-get install php7.2 php7.2-cli php7.2-common

Step 4 Install the Extensions For Laravel

These are the PHP extensions that Laravel 5.8 requires:

  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension
  • BCMath PHP Extension

First install the most popular PHP extensions:

sudo apt-get install php7.2-curl php7.2-gd php7.2-json  php7.2-mbstring php7.2-intl php7.2-mysql php7.2-xml php7.2-zip

Then add the extensions specific to Laravel:

sudo apt install -y php7.2-bcmath  php7.2-ctype

Restart to activate changes:

sudo systemctl restart apache2

Linux uses tar to decompress files while some of the files for PHP come in zip format, so here is the command to install zip and unzip extensions as well:

sudo apt -y install zip

Step 6 Install git

We shall use git to install Laravel apps from github.com.

sudo apt install -y git

Step 5 Install redis

Redis is a database, cache and message in-memory broker. We are not going to use it in this tutorial, though, but we can install it now.

sudo apt install -y redis-server

Step 6: Install Composer

Laravel uses Composer to manage all of its dependencies.

Install curl to download the install script for Composer:

sudo apt install curl -y

Then, download the installer:

cd ~
sudo curl -s https://getcomposer.org/installer | php

To make it available globally, move it to /usr/bin:

sudo mv composer.phar /usr/local/bin/composer

You are installing Composer as root user and it will show a warning about it. Once we have the app installed, we shall give access to its folder to user laraveluser.

Step 7: Create an Example Laravel App

Apache stores the data it serves under /var/www/html. To create a new Laravel app, run:

composer create-project --prefer-dist laravel/laravel /var/www/html/blog

Here “blog” will be the name of the app.

When Composer asks if you want it to set up folder permissions, answer with y.

Run these two commands to enable access to folders storage and bootstrap/cache as without that access, Laravel will not run:

sudo chmod -R a+rw /var/www/html/blog/storage
sudo chmod -R a+rw /var/www/html/blog/bootstrap/cache

We can now give user laraveluser access to the app folder:

sudo chown -R laraveluser /var/www/html/blog

Ubuntu will ask you for passwords whenever you change or access something in the system so be sure to have them nearby.

Step 8: Configuring Apache

Edit Apache configuration file so that it will serve Laravel app by default. It is called 000-default.conf and is stored in directory /etc/apache/sites-enabled. Open it for editing:

sudo nano /etc/apache2/sites-enabled/000-default.conf

Find line which starts with DocumentRoot and replace it with this:

DocumentRoot /var/www/html/blog/public

Save and close the file.

Laravel requires Apache modulerewrite_ to also be enabled; do so by running:

sudo a2enmod rewrite

Finally, instruct Apache to use .htaccess files, with which Laravel configures Apache on the fly. Open Apache global configuration file for editing:

sudo nano /etc/apache2/apache2.conf

Under the block, you’ll find the following line:

AllowOverride None

Change it to

AllowOverride All

When you are done, save the file.

Again restart Apache so that it takes new configuration into account:

sudo systemctl restart apache2

You can now navigate to your domain in your browser. You should see the following:

Laravel is now installed properly.

What To Do Next

Now you have a Laravel app on your server. The server is set up but Laravel itself is not. Follow the article “How To Set Up a Laravel Application on Ubuntu 16.04” which will show you how to create a database, connect it to the app and set up environment for a Laravel app properly. This will enable you to further develop and test your app on this server.

When your app becomes ready for deployment and production, read the next article in the series, on “How To Set Up Laravel For Production: Ubuntu 16.04”.

Dusko Savic is a technical writer and Flutter programmer.

duskosavic.com

The post How To Install Laravel on Ubuntu 16.04 VPS appeared first on Low End Box.

How To Install CakePHP On Ubuntu 16.04 VPS

How To Install CakePHP On a Ubuntu 16.04 VPS

With this tutorial, you will be able to create a CakePHP environment from scratch, define a database, and automatically generate a working web app.

You will start with an empty black screen and within an hour have a small web site on a VPS.

What are we going to cover

  • installation of LAMP stack (Linux, Apache, MySQL, PHP),
  • creation of user which will have access to the app,
  • installation of CakePHP itself,
  • creation of the database for the app,
  • creation of the app itself, through the process known as baking.

PRE-REQUISITES

We shall install and deploy CakePHP on Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access

Step 1: Creating a Non Root User

Once you are logged in as root, you can create a new user account that you’ll use from now on. Root is useful for performing system administration tasks, but using it for ordinary tasks is error prone and risky.

We’ll call the new user cakeuser. To create it, run:

adduser cakeuser

Then, add it to the sudo group, so that you can run commands as sudo:

usermod -aG sudo cakeuser

Step 2: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Next, enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://SERVER_IP/. If that does not work, try adding :80 in the end, like this:

http://SERVER_IP:80

You should see a welcome page for Apache, which means that you now have Apache running.

Step 3: Install MySQL Database

To install MySQL database, run the following command:

sudo apt install mysql-server -y

This will install the MariaDB database server (an enhanced fork of MySQL). You will be asked to enter a password for the MySQL root user. (Use Tab key from the keyboard to switch to the OK button and press Enter on the keyboard.)

Then secure MySQL installation by running:

sudo /usr/bin/mysql_secure_installation

Depending on the level of security you wish to achieve, you’ll have the option to adjust the minimum password complexity. Press 2 to select the highest level. Answer y to every prompt you get afterwards.

So you enter one password first, to enable access to MySQL, then ener another password to secure the installation. Store that second password as you will need it in Step 9 of this article.

To make it run on every system boot, enable it via systemctl:

sudo systemctl enable mysql

Step 4: Install PHP

Finally, install PHP by running:

sudo apt install php -y

This will install PHP 7.0, which will here serve just fine.

You’ll then need to install common PHP extensions that CakePHP requires:

sudo apt install php-{bcmath,bz2,intl,gd,mbstring,mcrypt,mysql,zip,intl,xml} libapache2-mod-php unzip -y

Linux uses tar to decompress files while some of the files for PHP come in zip format, so the above line will install zip and unzip programs as well.

Step 5: Install Composer

Composer is a flexible PHP package manager, which CakePHP uses to manage all of its dependencies.

Install curl to download the install script for Composer:

sudo apt install curl -y

Then, download the installer:

cd ~
sudo curl -s https://getcomposer.org/installer | php

To make it available globally, move it to /usr/bin:

sudo mv composer.phar /usr/local/bin/composer

You are installing Composer as root user and it will show a warning about it. Once we have the app installed, we shall give access to its folder to user cakeuser.

Step 6: Create an Example CakePHP App

Apache stores the data it serves under /var/www/html. To create a new app, run:

composer create-project --prefer-dist cakephp/app /var/www/html/cakeapp

Here “cakeapp” will be the name of the app. You may install several CakePHP apps in this way on the same server, just change “cakeapp” for the new name.

When Composer asks if you want it to set up folder permissions, answer with y.

If for some reason you later get a warning that these folders are not accessible, you may run these two commands:

sudo chmod -R a+rw /var/www/html/cakeapp/logs
sudo chmod -R a+rw /var/www/html/cakeapp/tmp

In Step 11 of this tutorial we shall use bake command in CakePHP to create a ready made app. For now, let us create a permission to access it:

cd /var/www/html/cakeapp
chmod +x bin/cake

We can now give user cakeuser access to the app folder:

sudo chown -R cakeuser /var/www/html/cakeapp

Have your passwords always easily accessible as Ubuntu will ask you for them whenever you change or access something in the system.

Step 8: Configuring Apache

Edit Apache configuration file so that it will serve CakePHP app by default. It is called 000-default.conf and is stored in directory /etc/apache/sites-enabled. Open it for editing:

sudo nano /etc/apache2/sites-enabled/000-default.conf

Find line which starts with DocumentRoot and replace it with this:

DocumentRoot /var/www/html/cakeapp/webroot

Save and close the file.

CakePHP requires Apache module_rewrite to also be enabled; do so by running:

sudo a2enmod rewrite

Finally, instruct Apache to use .htaccess files, with which CakePHP configures Apache on the fly. Open Apache global configuration file for editing:

sudo nano /etc/apache2/apache2.conf

Under the block, you’ll find the following line:

AllowOverride None

Change it to

AllowOverride All

When you are done, save the file.

Again restart Apache so that it takes new configuration into account:

sudo systemctl restart apache2

You can now navigate to your domain in your browser. You should see the following:

CakePHP is now installed properly, save for the fact that there is no database to connect to. We shall first create the database and then connect it to CakePHP in the next step.

Step 9 – Creating a Database

Launch MySQL shell:

sudo mysql -u root -p

When asked, enter the second password from Step 3 of this tutorial.

Once in MySQL prompt, copy and paste the following code as a whole, then press Enter on the keyboard:

CREATE DATABASE blogdb;
USE blogdb;
CREATE TABLE posts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);
    INSERT INTO posts (title, body, created)
    VALUES ('Sample title', 'This is the article body.', NOW());
    GRANT ALL PRIVILEGES ON blogdb.* TO 'post_user'@'localhost' IDENTIFIED BY 'password9I%';
    FLUSH PRIVILEGES;
    EXIT;

That will execute everything at once. Here is what it will look like in the terninal:

The first line will create a database blogdb and from the second line on, will start using it. Then we create table called posts with two visible fields, title and body. Columns id, created, and modified are necessary but will be used by CakePHP only internally.

Then we populate table posts by inserting one sample value.

The next line, starting with GRANT ALL PRIVILEGES is crucial. It creates a new user called _postuser and grants it all privileges on database blogdb. Currently there is only one table in this database, posts.

The third part, starting with IDENTIFIED BY, defines the password. It must contain lower and uppercase letters, as well as digits and special characters. Be sure to always change and invent new passwords for database users.

Command FLUSH PRIVILEGES; reloads the database with the changes made. The last command is EXIT, to leave the MySQL prompt and go back to the command line in Ubuntu itself.

Step 10: Connecting App to the Database

Navigate to the app folder:

cd /var/www/html/cakeapp/

CakePHP stores database credentials in a file named app.php, stored under the config folder. Open it for editing:

sudo nano /var/www/html/cakeapp/config/app.php

Find the Datasources block:

    'Datasources' => [
        'default' => [
            'className' => 'CakeDatabaseConnection',
            'driver' => 'CakeDatabaseDriverMysql',
            'persistent' => false,
            'host' => 'localhost',
            ...
            //'port' => 'non_standard_port_number',
            'username' => 'post_user',
            'password' => 'password9I%',
            'database' => 'blogdb',

In your terminal it may look like this:

For ‘username’ put your database user’s user name (post_user), for ‘password’ put your database user’s password (password9I%), and for database name it is obvious what to put (blogdb).

Save and close the file.

Refresh app in your browser and observe the success message under the Database section.

Step 11: Creating Your First CakePHP App

Under normal circumstances, you would have to now learn programming in PHP, then learn CakePHP, and within a couple of days, weeks or months, you would have your first “Hello World” app on the server.

There is a much faster way – using the bake command. Execute this:

./bin/cake bake all posts

It will create CakePHP code in various folders and produce an app that can read, save, update and delete entries in table posts of database blogdb.

Part of the bake output is shown here:

Visit the address in the browser:

http://SERVER_IP/posts

That’s it, we now have a CakePHP app installed, connected to the database and running for real.

What To Do Next

Now you have a rudimentary CakePHP app on your server. The rest depends on your original intentions. For example, if you are a developer selling sites to the clients, at this point you can upload your CakePHP app and be sure that it will run properly.

Once you finish your app, see article “How To Set Up CakePHP For Production: Ubuntu 16.04” how to improve your site before going to production phase.

Dusko Savic is a technical writer and Flutter programmer.
duskosavic.com

The post How To Install CakePHP On Ubuntu 16.04 VPS appeared first on Low End Box.

How to Replace Apache with NGINX on Ubuntu 18.04

NGINX is the modern web server founded by computer software engineer Igor Sysoev in the year 2004. NGINX is used by the most busiest and high traffic website. NGINX works out of box with the most major web stacks including LEMP (Linux, NGINX, MySQL, PHP) stack. This tutorial assumes that your website is hosted with the Apache web server and you want to migrate to NGINX . The process of migration includes replacing the Apache web server with the NGINX without loosing the website data with less downtime.

Why Replace Apache with NGINX ?

There are several reasons to replace Apache with NGINX are:

  • NGINX is the fastest web server that supports concurrent connections and supports high traffic website load.
  • NGINX consumes less RAM and CPU compared to Apache and it is resource friendly.
  • NGINX improves performance of website by supporting inbuilt cache system for faster access for website static contents like Images, CSS, JavaScript, etc.

What is the major difference between Apache and NGINX?

These are the major difference between Apache and NGINX are:

  • The main configuration files for Apache and NGINX are located at /etc/apache2/apache2.conf and /etc/nginx/nginx.conf respectively.
  • NGINX uses server block but Apache uses virtual host.
  • NGINX and Apache both are using same default root directory /var/www/html.
  • NGINX has inbuilt cache system but Apache don’t have any inbuilt cache system.

Pre Requirements

Before starting the tutorial you will need:

  • You will need a Ubuntu 18.04 VPS with minimum 1GB of RAM for smooth operations.
  • The Apache web server must be previously installed on your VPS.

Step-1: Remove the Apache Web Server

Before installing the NGINX you will remove the Apache web server to avoids conflict between them.

First of all you will stop the Apache service before removing the Apache web server. This enables us to remove the Apache without any issues.

$ sudo systemctl stop apache2

After stopping the Apache you will remove the startup Apache entries from systemctl. This enables us to remove the startup entries so that Apache services won’t be automatically started during boot time.

$ sudo systemctl disable apache2

When Apache services are successfully stopped and startup entries are also remove then it time to remove the Apache web server packages from the system.

$ sudo apt remove apache2

Above command will remove only apache2 packages on but Apache related dependencies are kept on with system. So it is essential to remove those unwanted dependencies to free your space. This can be run by given command.

$ sudo apt autoremove

Now, the Apache web server has successfully removed. The installation of NGINX is described in the next step.

Step-2: Install the NGINX Web Server

Let’s begin with the installation of NGINX on Ubuntu. The Ubuntu default repository contains all the packages of NGINX. Installation is straight forward so you have to install it without any hassle using apt package manager.

First remove and flush the old apt repository cache then update the repository to load latest packages information and perform a full upgrade to upgrade all the installed packages.

$ sudo apt clean all && sudo apt update && sudo apt dist-upgrade

After updating the repository it is the right time to install the updated NGINX packages.

$ sudo apt install nginx

When NGINX has successfully installed then Let’s begin with the next step that will guide you firewall configuration for NGINX web server.

Step-3: Configure UFW Firewall

The NGINX web server requires HTTP Port that is Port No. 80 and HTTPS port that is Port No. 443 to successfully work with firewall. So it is essential to keep this port open for that purpose so that NGINX works flawlessly. The UFW (Unified Firewall) is the default firewall for Ubuntu 18.04 Linux distribution. Hence, you will add firewall rules to allow HTTP and HTTPS ports.

By Default there is no rules are added to UFW firewall so it is so easy to add those rules. You are required to add the HTTP and HTTPS port rules to UFW firewall this can be done by simple commands. The NGINX Full rules contains both the HTTP and HTTP ports and this will allow these ports to be kept open by the UFW firewall.

$ sudo ufw allow "Nginx Full"

After adding the firewall rules its time to check the rules which had been added or updated using these rules using status command.

$ sudo ufw status

The above command show given sample output.

Status: active

To Action From
-- ------ ----
80/tcp ALLOW Anywhere
443/tcp ALLOW Anywhere
22/tcp LIMIT Anywhere
Nginx Full ALLOW Anywhere
80/tcp (v6) ALLOW Anywhere (v6)
443/tcp (v6) ALLOW Anywhere (v6)
22/tcp (v6) LIMIT Anywhere (v6)
Nginx Full (v6) ALLOW Anywhere (v6)

Above output shows that you have successfully added the firewall rules and you ready to move forward to configure the NGINX web server that is described in next step.

Step-4: Understanding the Configuration File of NGINX Web Server Compared to Apache Web Server

The configuration of NGINX are almost same like Apache web server but the structure and syntax is different referred to configuration files. This Difference between the can be understand by the given sample configuration file of Apache and NGINX

Sample Apache Configuration file is located at /etc/apache2/sites-available/example.com.conf

ServerName example.com
ServerAlias www.example.com
ServerAdmin admin@example.com
DocumentRoot /var/www/html/



Require all granted
AllowOverride None

Sample NGINX Configuration file is located at /etc/nginx/sites-available/example.com.conf

server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;

location / {
try_files $uri $uri/ =404;
}
}

If you look carefully from the both the configuration files you will find that Apache configuration file are expressed in virtual host and NGINX configuration file are expressed in server block. After understanding the difference between the configuration file of Apache and NGINX. Now, you ready to configure the rest of the NGINX configuration files that is described in next step.

Step-5: Configure NGINX Web Server

The NGINX has same capabilities like Apache web server but it has faster support of concurrent connections. The configuration file of NGINX uses the server blocks in configuration. You have to configure it wheres the same location of document root where all your static web assets like HTML, CSS, JavaScript and Images are stored.

Note: In this guide we throughout assume that your document root is /var/www/html and default domain name is example.com

In Ubuntu, the NGINX Server Blocks are located at sites-available and sites-enabled directory inside the NGINX configuration directory. You will edit the server blocks files located in /etc/nginx/sites-available/ and you will be create one for enabling the server blocks for your domain. This method is highly recommended because it allows you to host more than one website and at different domains and files locations on your Ubuntu.

$ sudo nano /etc/nginx/sites-available/example.com.conf

Add the given lines and don’t forget to replace example.com and www.example.com with your base domain name and subdomain to enable server blocks for NGINX.

server { 
listen 80; 
server_name example.com www.example.com; 
root /var/www/html; 

location / { 
try_files $uri $uri/ =404; 
} 
}

When you will completely add all of these lines then hit Ctrl + O to save and Ctrl + X to exit from nano text editor.

In NGINX server blocks configuration files you will create the symbolic link using soft links between sites-available and sites-enabled directory. Soft links allows you whenever you will make changes to server blocks configuration file located in sites-available directory and it will immediately replicated to sites-enabled directory.

$ sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf

You will check for correct syntax and to avoid any error present in NGINX configuration files. This command will also tells you where you have errors are present.

$ sudo nginx -t

When all syntax is correct then it will shows you Syntax OK as a output. If any thing goes wrong please re-check NGINX server blocks files. When all steps are completed then restart the services for making changes in the effect.

$ sudo systemctl restart nginx

After all things are ready then you will change the permission for default NGINX user www-data to enable read, write and execute permissions for default web root directory.

$ sudo chown www-data:www-data /var/www/html

To verify whether the www-data user and groups are owned the default web root directory by running the given long listing command

$ ll /var/www/html

After running this command the output shows www-data user and group is owned by the default web root directory /var/www/html . This means default NGINX user www-data will able to read, write and execute the default web root directory.

Conclusion

Lastly, you have successfully replaced the Apache to NGINX. Now you will ready to use the NGINX for your web property to enable fast access to web assets and low memory foot-printing. In the end, the NGINX can be used for various proposes and it can be used for both static and dynamic websites. For more information regarding the NGINX refer the man pages available in Ubuntu.

The post How to Replace Apache with NGINX on Ubuntu 18.04 appeared first on Low End Box.

How to Secure Apache with Let’s Encrypt Ubuntu 16.04

In this tutorial, we will examine how to secure Apache with Let’s Encrypt for the Ubuntu 16.04 operating system.   We will first examine an overview of Let’s Encrypt, certificate authorities, and then dive into a step by step guide to install & configure Let’s Encrypt on your Ubuntu 16.04 VPS servers and the review how to automatically renew SSL certificates.

What is Let’s Encrypt?

Let’s Encrypt is a free, automated, and open Certificate Authority (CA), that provides the ability to secure a website. Let’s Encrypt also provides automation and tools to reduce setup and maintenance challenges needed to secure web servers using HTTPS (SSL/TLS).


Why use Let’s Encrypt as your Certificate Authority?

Let’s Encrypt is free, easy to create, configure, and renew certificates on web servers (like Apache).

Most administrators who host web servers have a goal of attracting new visitors along with retaining end-user attention – as this often translates into profits or a growing website community. People hosting web servers also want to reduce maintenance and cost.

End users, on the other hand, are motivated to visit websites that are safe and do not compromise their security.

To satisfy both administrators and end users, a Certificate Authority is used to validate the authenticity of the web server’s domain name.

Traditional CA (Certificate Authorities) solutions like Verisign required domain owners to pay a fee to use the CA services, this is no longer required when using Let’s Encrypt. The Let’s encrypt service is funded by sponsors and donors.


How Certificate Authority works

  1. The web server admin creates a private and public key pair. Using the public key the website admin will create a CSR (certificate signing request) and then send the CSR to a Certificate Authority.
  2. The Certificate Authority signs the CSR and returns a final certificate that the web server admin will install on their web server.
  3. The final certificate is signed by the Certificate Authorities private key and holds metadata about the admin’s web server.
  4. When a website visitor goes to the web page, the visitor’s browser will download the final certificate from the web server. The visitor’s browser will contact the Certificate Authority to make sure that the certificate downloaded from the website is valid.
  5. If the Certificate authority confirms that the certificate is authentic/valid, the website visitor will receive a green padlock in their browser in the URL address box. This will notify the end user that the website is safe to visit.


Prerequisites to installing Let’s Encrypt on Ubuntu

  1. You must be an administrator of the domain name you want to secure; for this tutorial, we will be using the DNS hostname “LetsEncryptTutorial.ddns.net.
  2. You need to have your public IP address.
  3. You must install Apache web server if it’s not already installed.


Install Apache

  1. Update the Ubuntu apt repository package definitions. Open a command line terminal and type “apt-update” or if you are logged in as a non-root user, type “sudo apt update”.

  1. To Install Apache: “apt install apache2 -y” or “sudo apt install apache2 -y”

  1. Change into the directory called /var/www/html and ensure an index.html file exists in the directory.

  1. Optional but recommended: Edit the default index.html title to be unique (example: Let’s Encrypt tutorial website) by adding “Let’s Encrypt tutorial” to the body. NOTE: This is simply to help you confirm the server is resolving and you are not accessing cached pages.

  1. If using systemd for startup restart Apache “systemctl restart apache2” or “sudo systemctl restart apache2” if using non-root user. If using init run “service apache2 restart”

  1. Confirm Apache is running properly on your system. If using systemd use “systemctl status apache2” and if using init use “service apache2 status”

  1. Confirm that the modified default Apache website is now available via a web browser

First, confirm that port 80 is open and working by going to the following URL,
http://:80 (you should see your edited webpage)

Next, confirm that the web server SSL port 443 is also open and working by going to the following,
https://:443

NOTE: When the server resolves in a browser using port 443 you will get a “Not Encrypted” or “Not Secure” error in the address bar. That’s ok.

Caution: Do not proceed to the following steps if you are not able to successfully reach your Apache server on both ports 80 and 443. If the server does not resolve to either port contact your network admins to ensure that both ports are configured to allow web traffic.

Once we know Apache is resolving correctly, we can move on to the next section of this tutorial.


How to set up Let’s Encrypt on Apache

  1. Install common tools “apt-get install software-properties-common -y” if logged in as root user

  1. Add the apt component for installing new repositories, by running: “add-apt-repository universe”

  1. Add certbot to the list of apt repositories “add-apt-repository ppa:certbot/certbot”

  1. Update apt to detect the newly added repositories: “apt update”

  1. Install certbot to create and renew certificates using let’s encrypt: “apt-get install certbot python-certbot-apache -y”

  1. Run the certbot command to create SSL for your domain.

  1. Now visit https:// to verify that your new certificate works properly and your website has a valid certificate. You will notice a green lock icon confirming a secured connection is established with your Apache server. Click the green lock to get details about the SSL certificate.


How to automate the renewal of Let’s Encrypt

It is highly recommended to automate the renewal of your certificate to avoid http traffic interruption due to an expired SSL certificate. For Example; on the Apache server you can create a cron job to renew the certificate every month on the 10th at 6:04 am using cron by typing “sudo crontab -e” and at the bottom add the following line (below) and save/exit.

4 6 10 * * certbot –apache –force-renewal renew –quiet


EOF

The post How to Secure Apache with Let’s Encrypt Ubuntu 16.04 appeared first on Low End Box.

Install and Secure phpMyAdmin on Ubuntu 16.04 VPS

With this tutorial, you will be able to install and secure phpMyAdmin, the most popular program for accessing MySQL and MariaDB databases on Internet servers.

What We Are Going To Cover

  • Installing the LAMP stack (Linux, Apache, MySQL, PHP)
  • Adding PHP extensions to run phpMyAdmin
  • How to install phpMyAdmin itself

To secure phpMyAdmin, we are going to:

  • Install Let’s Encrypt
  • Edit php.ini to eliminate showing of PHP errors
  • Restrict access to folders templates and libraries
  • Prevent robots from accessing phpMyAdmin
  • Hide phpMyAdmin behind an authentication proxy
  • Change the URL of phpMyAdmin

Prerequisites

We will install and deploy phpMyAdmin on :

  • a clean installation of Ubuntu 16.04,
  • with at least 512Mb of RAM available on the server and
  • at least 15Gb free disk space.
  • You will need root user access.

To install Let’s Encrypt certificates

  • You must have DNS records for your your domain already set up to point to your VPS.

Step 1: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://YOUR_DOMAIN/. If that does not work, try adding :80 in the end, like this:

http://YOUR_DOMAIN:80

You should see a welcome page for Apache, which means that you now have Apache running.

Step 2: Install PHP 7.3

At the time of this writing, phpMyAdmin requires a version of PHP 7.1.0 or newer to be installed. We shall install PHP 7.3. First, install the prerequisite packages:

sudo apt install software-properties-common python-software-properties

Then, add the ondrej PPA:

sudo add-apt-repository -y ppa:ondrej/php

and update your sources by running:

sudo apt update

Install PHP 7.3 using the following command:

sudo apt install php7.3 php7.3-cli php7.3-common

Step 3: Install Required PHP Extensions

The PHP extensions that phpMyAdmin requires are:

  • session support, the Standard PHP Library (SPL) extension, hash, ctype, and JSON support
  • mbstring, zip, gd. openssl, libxml, curl

Install them:

sudo apt install php7.3-curl php7.3-gd php7.3-json  php7.3-mbstring php7.3-intl php7.3-mysql php7.3-xml php7.3-zip

Restart Apache to activate:

sudo systemctl restart apache2

Step 4: Install MariaDB

Install MariaDB database with the following command:

sudo apt install mysql-server -y

This will install MariaDB database server (an enhanced fork of MySQL). You will be asked to enter password for the MySQL root user. (Use Tab key from the keyboard to switch to the OK button and press Enter on the keyboard.)

Then, secure MySQL installation by running:

sudo /usr/bin/mysql_secure_installation

Press 2 to select the highest level of password complexity. Answer y to every prompt you get afterwards.

So you enter one password first, to enable access to MySQL, then enter another password to secure the installation. Store that second password as you will need it in Step 5 of this article.

To make it run on every system boot, enable it via systemctl:

sudo systemctl enable mysql

Step 5: Install phpMyAdmin From Ubuntu Repository

It is possible to install phpMyAdmin via Composer and Git, but the easiest way is to pull it from the Ubuntu repository:

sudo apt install phpmyadmin php-mbstring php-gettext

You will see this window:

Press space on the keyboard, otherwise the Apache option will NOT be checked. Then, press Tab and Enter to finish data entry in this window.

Press Enter in the next window to let the installer configure a suitable database for phpMyAdmin for you.

In the next screen, enter a password with which phpMyAdmin will connected to the database. That will be the second password from Step 4:

The installation process created files phpmyadmin.conf in directory /etc/apache2/conf-enabled/. Apache will automatically read in all files in that directory.

Execute the following command to see the new file:

ls /etc/apache2/conf-enabled/

Finally, restart Apache so that all these changes take effect:

sudo systemctl restart apache2

Step 6: Securing You Site To Serve Only HTTPS

If you have a domain name and DNS records properly set up to point to your VPS, you can use certbot to generate Let’s Encrypt certificates. This means that you will always access phpMyAdmin (and the rest of your YOUR_DOMAIN) via HTTPS.

We will folow the original documentation to install Let’s Encrypt. Choose Apache for software and Ubuntu 16.04 (xenial) for System – it should look like this:

The site will then generate the following commands for you to enter into the command prompt of your VPS:

sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository universe
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot python-certbot-apache 
sudo certbot --apache

You will be asked for the DNS name of your site and whether you want to route all traffic from HTTP to HTPPS. Choose this option as that is the sole reason of installing Let’s Encrypt in the first place.

Now that the access to site is secure behind HTTPS, we can access phpMyAdmin for the first time, without fear that someone could sniff our database user name and password.

Go to this address in your browser:

http://YOUR_DOMAIN/phpmyadmin

Note that this address started with HTTP, but it will end up as HTTPS.

You should see the familiar interface of phpMyAdmin:

Step 7: Securing the Instance of phpMyAdmin

There are several ways to secure the instance of phpMyAdmin. We will show only those that do not require access to phpMyAdmin source code.

Edit php.ini To Eliminate Showing of PHP Errors

Open the config file for PHP and eliminate showing of the errors for all PHP apps:

sudo nano /etc/php/7.3/apache2/php.ini

With Ctrl-W search for “Error handling and logging”. You’ll see something like this:

You will want to change the so-called production values in that document.

We want to turn off any errors tht PHP might return. Find row that starts with errorreporting_ and set it to off or to this:

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

(Optional) Restrict Access to Folders templates and libraries

Folders templates and libraries in your phpMyAdmin installation must not be accessed by non-authorized visitors. This kind of protection should be installed right from the start, but if that is not the case, here is how we can allow only, say, the root user to access these folders:

sudo chown -R root:root /usr/share/phpmyadmin/templates
sudo chmod 0750 /usr/share/phpmyadmin/templates
sudo chown -R root:root /usr/share/phpmyadmin/libraries
sudo chmod 0750 /usr/share/phpmyadmin/libraries

Prevent Robots From Accessing phpMyAdmin

To prevent robots from accessing your phpMyAdmin installation, create a .htaccess file:

sudo nano /usr/share/phpmyadmin/.htaccess

then enter the following text into it:

RewriteEngine on

RewriteCond %{REQUEST_METHOD} !^(GET|POST)$ [NC,OR]

RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget).* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(libwww-perl|curl|wget|python|nikto|wkito|pikto|scan|acunetix).* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner).* [NC,OR]

intext:"Cookies must be enabled"
RewriteCond %{HTTP_USER_AGENT} ^.*(AdsBot-Google|ia_archiver|Scooter|Ask.Jeeves|Baiduspider|Exabot|FAST.Enterprise.Crawler|FAST-WebCrawler|www.neomo.de|Gigabot|Mediapartners-Google|Google.Desktop|Feedfetcher-Google|Googlebot|heise-IT-Markt-Crawler|heritrix|ibm.comcs/crawler|ICCrawler|ichiro|MJ12bot|MetagerBot|msnbot-NewsBlogs|msnbot|msnbot-media|NG-Search|lucene.apache.org|NutchCVS|OmniExplorer_Bot|online.link.validator|psbot0|Seekbot|Sensis.Web.Crawler|SEO.search.Crawler|Seoma.[SEO.Crawler]|SEOsearch|Snappy|www.urltrends.com|www.tkl.iis.u-tokyo.ac.jp/~crawler|SynooBot|crawleradmin.t-info@telekom.de|TurnitinBot|voyager|W3.SiteSearch.Crawler|W3C-checklink|W3C_Validator|www.WISEnutbot.com|yacybot|Yahoo-MMCrawler|Yahoo!.DE.Slurp|Yahoo!.Slurp|YahooSeeker).* [NC]
RewriteRule .* - [F]

This may be just a beginning in your battle against the robots, but the code above is a good start.

Hiding phpMyAdmin Behind an Authentication Proxy

You can force your users to enter login details before accessing phpMyAdmin. To that end, configure your web server to request HTTP authentication. Open the phpmyadmin.conf file for editing:

sudo nano /etc/apache2/conf-available/phpmyadmin.conf

Find the following line in nano editor: “Directory /usr/share/phpmyadmin”. Add the line “AllowOverride All”, then save and close the file.

This is what it will look like in the editor:

Restart Apache for these changes to take effect:

sudo systemctl restart apache2

Now Apache can read .htaccess file for phpmyadmin folder, but we haven’t created that file as yet. Create it by running:

sudo nano /usr/share/phpmyadmin/.htaccess

Enter the following text:

AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/phpmyadmin/.htpasswd
Require valid-user

Save and close the file.

Here is what the commands in this file do:

  • AuthType defines what kind of authentification will be used. “Basic” means it will ask for a password.
  • AuthName is the name of the rule applied for authentication. In our case, that is a string that will appear in the dialogue when asking user for login details.
  • AuthUserFile – where will the password file reside? We are going to create this file outside of the usual paths for files.
  • Require – Who will have access to the main site? In this case, only valid users will have it, while none of the others will be let in.

Now, create a password file with the following command:

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

Executing it will define a user called username in the password file, and will ask for a password. Store that password in a secure place as you will need it as soon as you visit the address

http://YOUR_DOMAIN/phpmyadmin

You will see a form prompting you to enter a username and password:

Once you enter it successfully, you will be redirected to another form asking for login details.

Into that second form, enter login credentials for the database. You can log in as root using the password you set up previously, in Step 4.

Changing the URL of phpMyAdmin

Instead of using a very obvious name of /phpmyadmin, you can use something else. Access the configuration file like this:

sudo nano /etc/apache2/conf-available/phpmyadmin.conf

Put phpmyadmin234 instead of phpmyadmin. Here is how the relevant part in the editor may look like:

Use this address in your browser to access phpmyadmin:

http://YOUR_DOMAIN/phpmyadmin234

Restart Apache to activate:

sudo systemctl restart apache2

This is a “security through obscurity” approach at work. Most bots won’t try other paths except the default one anyways.

Dusko Savic is a technical writer and Flutter programmer.

duskosavic.com

The post Install and Secure phpMyAdmin on Ubuntu 16.04 VPS appeared first on Low End Box.

Set Up And Configure Postfix E-Mail Server with Dovecot On Ubuntu 16.04

Set Up And Configure Postfix E-Mail Server with Dovecot

With this tutorial, we assume that you have already installed Postfix, an open-source mail transfer agent. After that, we install and configure Dovecot, an open source IMAP and POP3 email server for Linux/UNIX-like systems.

Finally, we shall install SquirrelMail, a mail user interface, to show that Postfix and Dovecot really work.

What We Are Going To Cover

  • How to install Apache and PHP 7.3
  • Install Postfix mail server
  • Installing Dovecot as a mail client
  • Install and configure SquirrelMail
  • Annuling errors in SquirrelMail installation
  • Creating a user which will send and receive mail
  • Send mail from SquirrelMail

Prerequisites

We use Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access and
  • DNS records for your domain must be already in place, especially PTR and MX.
  • In this post we assume that you have worked through “How To Install And Configure Postfix“, and that you have Postfix up and running as instructed.

We start from scratch and install all that we need to finish up with a running SquirrelMail.

Step 1: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://YOUR_DOMAIN/. If that does not work, try adding :80 in the end, like this:

http://YOUR_DOMAIN:80

You should see a welcome page for Apache, which means that you now have Apache running.

Step 2: Install PHP 7.3

First, install the prerequisite packages:

sudo apt install software-properties-common python-software-properties

Then, add the ondrej PPA:

sudo add-apt-repository -y ppa:ondrej/php

and update your sources by running:

sudo apt update

Install PHP 7.3 using the following command:

sudo apt install php7.3 php7.3-cli php7.3-common

Step 3: Install PHP Extensions

These are the usual extensions that many programs expect to be there:

  • session support, the Standard PHP Library (SPL) extension, hash, ctype, and JSON support
  • mbstring, zip, gd. openssl, libxml, curl

Install them:

sudo apt install php7.3-curl php7.3-gd php7.3-json  php7.3-mbstring php7.3-intl php7.3-mysql php7.3-xml php7.3-zip

Restart Apache to activate:

sudo systemctl restart apache2

Step 4: Install Postfix Mail Server

We have gone over installation of Postfix in some length in article “How To Install And Configure Postfix“. Here we only repeat the commands:

sudo apt-get install postfix

Select Internet site, and enter FQDN site name, for instance, aleksasavic.com. Next restart Postfix:

sudo service postfix restart

Step 5: Install Dovecot

Postfix is the mail server while Dovecot is a mail delivery agent (MDA). They cooperate as Dovecot delivers the emails from/to Postfix.

Dovecot is a secure IMAP server. It silently indexes email messages in the background, and will replace most other IMAP clients. Besides Postfix, it works with Exim as well, and will even offer workarounds for some bugs present in other IMAP and POP3 clients

For the basic installation of Dovecot, only two commands are needed:

sudo apt-get install dovecot-imapd dovecot-pop3d
sudo service dovecot restart

Step 6: Install SquirrelMail

SquirrelMail is a standards-based webmail package written in PHP. It includes built-in pure PHP support for the IMAP and SMTP protocols, and all pages render in HTML 4.0 (with no JavaScript required) for maximum compatibility across browsers. It has few requirements and is easy to configure and install. SquirrelMail also supports MIME, address books, and folder manipulation.

Here is how to install it:

sudo apt-get install squirrelmail
sudo squirrelmail-configure

Step 7: Configuring SquirellMail

Now we need to configure SquirrelMail, through a special command:

sudo squirrelmail-configure

We are met with a series of textual menus.

Enter 2 for server settings and another menu:

Now select 1 to change domain name to your domain name.

To go back, enter R and press Enter on the keyboard.

Next to change is option 4 for General Options.

We go after option “Allow server-side sorting”; enter “11” and change it from “false” to “true” by entering “y”. Press Enter on the keyboard, and enter the “S” key to save the configuration file.

Finally, Q to quit.

Now we copy squirrel configuration files to apache:

sudo cp /etc/squirrelmail/apache.conf /etc/apache2/sites-available/squirrelmail.conf
sudo a2ensite squirrelmail.conf && sudo service apache2 reload

Restart Apache to activate:

sudo systemctl restart apache2

We have installed Postfix, Dovecot, and SquirrelMail. Now we should be able to see SquirrelMail in action, by navigating to

aleksasavic.com/squirrelmail

in the browser.

Step 8: Create Email User

Let us now define a user which will have access to the mail:

sudo useradd squser
sudo passwd squser
sudo mkdir -p /var/www/html/squser

We also have to state permissions for the aquser:

sudo chown -R squser:squser /var/www/html/squser

Login into your mail again. If there are directories without permissions, execute these commands:

sudo chmod 777 /var/mail
sudo chmod 777 /var/www
sudo chmod 777 /home

Step 9: Resolving Errors

If there are errors, have a look at errors log:

sudo nano /var/log/mail.err

and find what the complaint is about. In this case:

mkdir(/home/squser/mail) failed: Permission denied (
euid=1002(squser) egid=1002(squser) missing +w perm: /home,

so we need to give writing permission to folder /home:

sudo chmod 777 /home

Execute command

/etc/init.d/postfix reload

to activate the changes we have just created. Restart Postfix:

sudo service postfix restart

Step 10: Encrypt Mail with Standard TLS

Email started out as sending plain text from sender to recipient. That is not safe, so the messages should be encrypted — protected while in transfer. Only the intended recipient should be able to read them.

We shall now protect the transfer with standard protocol STARTTLS:

sudo postconf -e 'smtptlssecuritylevel = may'
sudo postconf -e 'smtpdtlssecuritylevel = may'
sudo postconf -e 'smtptlsnotestarttlsoffer = yes'
sudo service postfix restart

Step 11: Send Email From SquirrelMail

Let us return to the browser, we should enter user name and password. User name is the name of the user that we created, such as squser and password to enter is its password from Ubuntu.

Enter SquirrelMail. If everything goes well, we shall see good old SquirrelMail on the screen. You should be able to send messages immediately, while to receive them, you would have to set up an MX parameter at your registrar’s site. You might also need to configure Postfix a bit more, which is out of scope of this article.

What To Do Next

SquirrelMail is a mature application and its development has stopped five years ago. You can still run it in production environment and it won’t fail you. You may also want to install another email client such as RoundCube, which is much harder to install but is well maintained and more powerful compared to SquirrelMail.

Dusko Savic is a technical writer and Flutter programmer.

duskosavic.com

The post Set Up And Configure Postfix E-Mail Server with Dovecot On Ubuntu 16.04 appeared first on Low End Box.