Latest posts

Browse topics

How to Install Drupal with Nginx, PHP-FPM 7.4, MySQL, phpMyAdmin on Ubuntu 20.04 - Linode Guide

In this article, you will learn how to setup webserver for serving  Drupal  websites running with Nginx, PHP-FPM 7.4, MySQL and phpMyAdmin on Ubuntu 20.04

For the following tutorial, I used very much the information from my previous guide with Ubuntu 18.04, but I decided to rewrite it for Ubuntu 20.04 version as it is shipped with php7.4 version and will work for Drupal 7, Drupal 8 and most probably for Drupal 9

Prerequisites

  • Ubuntu 20.04 
  • Root privileges.

You can get a cheap VPS starting just $5/mo from Linode. That's what I did - bought a new nanode from Linode

Deploying server with Linode

Deploying server with Linode

Literally in a couple of seconds, the new server was up and running - that's what I love sticking with Linode for years

Follow basic security guide, see: Securing Your Server

I will use Putty for Windows to access SSH

Secure your server

Create the user, replacing example_user with your desired username. You’ll then be asked to assign the user a password:

adduser example_user


Add the user to the sudo group so you’ll have administrative privileges:

adduser example_user sudo

Disallow root logins over SSH. This requires all SSH connections to be by non-root users. Once a limited user account is connected, administrative privileges are accessible either by using sudo or changing to a root shell using su -.

sudo nano /etc/ssh/sshd_config

Under # Authetification section change to

# Authentication: ...

PermitRootLogin no

Update the Ubuntu system

sudo apt-get update

Install Nginx and PHP-FPM

Install Nginx with the following apt command:

sudo apt-get install nginx -y

Next, install php7.4-fpm with php-gd extension that is required by Drupal core:

sudo apt-get install php7.4-fpm php7.4-cli php7.4-gd php7.4-mysql php7.4-xml -y

Configure Nginx and PHP-FPM

In this step, we will configure Nginx to use php-fpm to serve HTTP requests for PHP pages. Go to the php-fpm directory "/etc/php/7.4/fpm" and edit the "php.ini" file:

sudo nano /etc/php/7.4/fpm/php.ini

Un-comment the cgi.fix_pathinfo line and change the value to "0"

When using nano command you can use CTRL+W to locate that line. Once changed press CTRL+O to save changes and CTRL+X to exit from nano editor

Now we should modify the default Nginx virtual host configuration. Edit the "default" file and enable the php-fpm directive.

sudo nano /etc/nginx/sites-available/default

Un-comment  location ~ \.php$ section, so it look like this

location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php7.4-cgi alone:
#fastcgi_pass 127.0.0.1:9000;
# With php7.4-fpm:
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}

CTRL+O and CTRL+X

Then test the Nginx configuration with the command "nginx -t" to ensure that it is valid:

nginx -t

If there is no error, restart nginx and the php-fpm service:

systemctl restart nginx
systemctl restart php7.4-fpm

PHP Info file (Optional)

Next, test that php-fpm is working properly with Nginx by creating new PHP info file in the web directory "/var/www/html"

cd /var/www/html/
echo "<?php phpinfo(); ?>" > info.php

Visit the info.php file at the server IP  in a web browser.

Configure the VirtualHost for Drupal

We will install Drupal 8 in the directory "/srv/www/0dtespxtrading.com". Please replace my domain name in your installation with the domain name of the website that you want to use this Drupal installation for. So let's create the directory:

sudo mkdir -p /srv/www/0dtespxtrading.com/{public_html,logs}
sudo usermod -a -G www-data admin
sudo chown -R www-data:www-data /srv/www
sudo chmod -R 775 /srv/www
sudo nano /etc/nginx/sites-available/0dtespxtrading.com

Paste the Nginx configuration for Drupal 8:

server {
    server_name 0dtespxtrading.com;
    root /srv/www/0dtespxtrading.com/public_html; ## <-- Your only path $
    access_log /srv/www/0dtespxtrading.com/logs/access.log;
    error_log /srv/www/0dtespxtrading.com/logs/error.log;

    listen 80;
    listen [::]:80;


    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        # try_files $uri @rewrite; # For Drupal <= 6
        try_files $uri /index.php?$query_string; # For Drupal >= 7
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    # In Drupal 8, we must also match new paths where the '.php' appears in the middle,
    # such as update.php/selection. The rule we use is strict, and only allows this pattern
    # with the update.php front controller.  This allows legacy path aliases in the form of
    # blog/index.php/legacy-path to continue to route to Drupal nodes. If you do not have
    # any paths like that, then you might prefer to use a laxer rule, such as:
    #   location ~ \.php(/|$) {
    # The laxer rule will continue to work if Drupal uses this new URL pattern with front
    # controllers other than update.php in a future release.
    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
        include fastcgi_params;
        include snippets/fastcgi-php.conf;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    }

    # Fighting with Styles? This little gem is amazing.
    # location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
    location ~ ^/sites/.*/files/styles/ { # For Drpal >= 7
        try_files $uri @rewrite;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}

CTRL+O and CTRL + X

The Drupal virtual host file has been created, now we have to activate it by creating a symlink to the file in the "sites-enabled" directory:

ln -s /etc/nginx/sites-available/0dtespxtrading.com /etc/nginx/sites-enabled/

Test the Nginx configuration and if there are no errors restart Nginx:

nginx -t
systemctl restart nginx

Install MySQL

sudo apt-get install mysql-server
​sudo mysql_secure_installation

Install phpMyAdmin

sudo apt-get install phpmyadmin

Hit ESC when the installation prompts you for auto-configuration because there is no option for Nginx.

Make an easily accessible symlink

sudo ln -s /usr/share/phpmyadmin/ /srv/www/0dtespxtrading.com/public_html/phpmyadmin

​

Install and Configure Drupal

Enter the directory that we created earlier and download Drupal with wget. I'm using the latest Drupal 8.8.6. release as of May 20, 2020, make sure you are downloading latest version by visiting Drupal 8 download page and writing down the last numbers (version)

cd /srv/www/0dtespxtrading.com
sudo wget https://ftp.drupal.org/files/projects/drupal-8.8.6.tar.gz
sudo tar -xvzf drupal-8.8.6.tar.gz
sudo cp drupal-8.8.6/* public_html/ -R
sudo chown www-data:www-data public_html -R

Now visit your Drupal site in the web Browser, you should see the following screen

Drupal 8 welcome screen

Drupal 8 welcome screen

Now, it's just time to connect the database and set up your Drupal 8 website

File Permissions for gmap_markers.js

Time after time I'm facing this issue with gmap markers. As mostly this happens when I'm doing something on the server side with file permissions, I decided to keep the notes

here is the problem

GMap is unable to save the marker bundle, so the markers will not work. Please check file system permissions of the public://js/gmap_markers.js!

Here is the solution

sudo chmod 755 /sites/all/files/js/gmap_markers.js

Simple CSS trick to Make Table Responsive

Working on the OptionsBrew.com project (website is powered by Drupal 8) I faced the following responsive table issue while browsing content with a table on smaller screens (phone)

Broken Table on smaller screens

Broken Table on a smaller screen

Luckily there is a simple CSS workaround:

in the .css file add the following to table properties:

   display: block;
   overflow-x: auto;

like this:

table{
    border-collapse: separate;
    border-spacing: 0;
    width:100%;
    margin: 25px 0 40px;
    display: block;
    overflow-x: auto;
}

here is how it looks now

Responsive table

Responsive table

You can see a live example here: Top 20 Most Active Stock Options May 2020

Poppy fields near Marneuli

We love poppy fields, we have featured them a couple of times here at the Piece of Life series

Today we are going to share a brief photo story with poppy field near Marneuli, next to the Милена Оптовый Магазин (Milena mall)

It was one of the first days when travel restrictions between Georgia's inner cities were lifted and we decided to head to the Marneuli side looking for poppy fields (my partner have seen online some beautiful photos of poppies the day before). I love these wandering around days.

We didn't find the special poppy field, instead we found poppies. Surprisingly we made a lot of great family portraits here rich with poppies  in the background.

Poppy fields next to the Milena Shopping mall near Marneuli

Poppy fields next to the Milena Shopping mall near Marneuli

Quite an interesting stop here, we spent about an hour in this flower field.

Poppy field

Poppy field

That was a nice day at the end of May 2020.

Drupal 7 Fix: SQLSTATE[42000]: Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER'.

I was migrating Drupal 7 website to a newer infrastructure (PHP 7.4) and during the migration process when tried to connect to the MySQL database  I faced following error - SQLSTATE[42000]: Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER'.

Here is the error code:

Resolve all issues below to continue the installation. For help configuring your database server, see the installation handbook, or contact your hosting provider.

Failed to connect to your database server. The server reports the following message: SQLSTATE[42000]: Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER'.

Is the database server running?
Does the database exist, and have you entered the correct database name?
Have you entered the correct username and password?
Have you entered the correct database hostname?

No_auto_create_user

No_auto_create_user

After quick research I was able to find a patch (Mysql 8 Support on Drupal 7 #24)  which involves overwriting core database.inc file (inclues/database/mysql - > database.inc)

here I'm pasting full working example (for a patch see here)

<?php

/**
 * @file
 * Database interface code for MySQL database servers.  
 */

/**
 * @addtogroup database
 * @{
 */

class DatabaseConnection_mysql extends DatabaseConnection {

  /**
   * Flag to indicate if the cleanup function in __destruct() should run.
   *
   * @var boolean
   */
  protected $needsCleanup = FALSE;

  public function __construct(array $connection_options = array()) {
    // This driver defaults to transaction support, except if explicitly passed FALSE.
    $this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);

    // MySQL never supports transactional DDL.
    $this->transactionalDDLSupport = FALSE;

    $this->connectionOptions = $connection_options;

    $charset = 'utf8';
    // Check if the charset is overridden to utf8mb4 in settings.php.
    if ($this->utf8mb4IsActive()) {
      $charset = 'utf8mb4';
    }

    // The DSN should use either a socket or a host/port.
    if (isset($connection_options['unix_socket'])) {
      $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
    }
    else {
      // Default to TCP connection on port 3306.
      $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
    }
    // Character set is added to dsn to ensure PDO uses the proper character
    // set when escaping. This has security implications. See
    // https://www.drupal.org/node/1201452 for further discussion.
    $dsn .= ';charset=' . $charset;
    $dsn .= ';dbname=' . $connection_options['database'];
    // Allow PDO options to be overridden.
    $connection_options += array(
      'pdo' => array(),
    );
    $connection_options['pdo'] += array(
      // So we don't have to mess around with cursors and unbuffered queries by default.
      PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
      // Because MySQL's prepared statements skip the query cache, because it's dumb.
      PDO::ATTR_EMULATE_PREPARES => TRUE,
    );
    if (defined('PDO::MYSQL_ATTR_MULTI_STATEMENTS')) {
      // An added connection option in PHP 5.5.21+ to optionally limit SQL to a
      // single statement like mysqli.
      $connection_options['pdo'] += array(PDO::MYSQL_ATTR_MULTI_STATEMENTS => FALSE);
    }

    parent::__construct($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);

    // Force MySQL to use the UTF-8 character set. Also set the collation, if a
    // certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
    // for UTF-8.
    if (!empty($connection_options['collation'])) {
      $this->exec('SET NAMES ' . $charset . ' COLLATE ' . $connection_options['collation']);
    }
    else {
      $this->exec('SET NAMES ' . $charset);
    }

    // Set MySQL init_commands if not already defined.  Default Drupal's MySQL
    // behavior to conform more closely to SQL standards.  This allows Drupal
    // to run almost seamlessly on many different kinds of database systems.
    // These settings force MySQL to behave the same as postgresql, or sqlite
    // in regards to syntax interpretation and invalid data handling.  See
    // http://drupal.org/node/344575 for further discussion. Also, as MySQL 5.5
    // changed the meaning of TRADITIONAL we need to spell out the modes one by
    // one.
    $connection_options += array(
      'init_commands' => array(),
    );
    $connection_options['init_commands'] += array(
     'sql_mode' => "SET sql_mode = 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO'",
    );
    // Execute initial commands.
    foreach ($connection_options['init_commands'] as $sql) {
      $this->exec($sql);
    }
  }

  public function __destruct() {
    if ($this->needsCleanup) {
      $this->nextIdDelete();
    }
  }
  public function query($query, array $args = array(), $options = array()) {
    $query = preg_replace('/{([^}]+)}/', '`\1`', $query);
    // This to make Drush work
    $query = str_replace(' system.', ' `system`.', $query);
    $query = str_replace('`system` system', '`system` `system`', $query);
    return parent::query($query, $args, $options);
  }

  public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
    return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
  }

  public function queryTemporary($query, array $args = array(), array $options = array()) {
    $tablename = $this->generateTemporaryTableName();
    $this->query('CREATE TEMPORARY TABLE {' . $tablename . '} Engine=MEMORY ' . $query, $args, $options);
    return $tablename;
  }

  public function driver() {
    return 'mysql';
  }

  public function databaseType() {
    return 'mysql';
  }

  public function mapConditionOperator($operator) {
    // We don't want to override any of the defaults.
    return NULL;
  }

  public function nextId($existing_id = 0) {
    $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
    // This should only happen after an import or similar event.
    if ($existing_id >= $new_id) {
      // If we INSERT a value manually into the sequences table, on the next
      // INSERT, MySQL will generate a larger value. However, there is no way
      // of knowing whether this value already exists in the table. MySQL
      // provides an INSERT IGNORE which would work, but that can mask problems
      // other than duplicate keys. Instead, we use INSERT ... ON DUPLICATE KEY
      // UPDATE in such a way that the UPDATE does not do anything. This way,
      // duplicate keys do not generate errors but everything else does.
      $this->query('INSERT INTO {sequences} (value) VALUES (:value) ON DUPLICATE KEY UPDATE value = value', array(':value' => $existing_id));
      $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
    }
    $this->needsCleanup = TRUE;
    return $new_id;
  }

  public function nextIdDelete() {
    // While we want to clean up the table to keep it up from occupying too
    // much storage and memory, we must keep the highest value in the table
    // because InnoDB  uses an in-memory auto-increment counter as long as the
    // server runs. When the server is stopped and restarted, InnoDB
    // reinitializes the counter for each table for the first INSERT to the
    // table based solely on values from the table so deleting all values would
    // be a problem in this case. Also, TRUNCATE resets the auto increment
    // counter.
    try {
      $max_id = $this->query('SELECT MAX(value) FROM {sequences}')->fetchField();
      // We know we are using MySQL here, no need for the slower db_delete().
      $this->query('DELETE FROM {sequences} WHERE value < :value', array(':value' => $max_id));
    }
    // During testing, this function is called from shutdown with the
    // simpletest prefix stored in $this->connection, and those tables are gone
    // by the time shutdown is called so we need to ignore the database
    // errors. There is no problem with completely ignoring errors here: if
    // these queries fail, the sequence will work just fine, just use a bit
    // more database storage and memory.
    catch (PDOException $e) {
    }
  }

  /**
   * Overridden to work around issues to MySQL not supporting transactional DDL.
   */
  protected function popCommittableTransactions() {
    // Commit all the committable layers.
    foreach (array_reverse($this->transactionLayers) as $name => $active) {
      // Stop once we found an active transaction.
      if ($active) {
        break;
      }

      // If there are no more layers left then we should commit.
      unset($this->transactionLayers[$name]);
      if (empty($this->transactionLayers)) {
        if (!PDO::commit()) {
          throw new DatabaseTransactionCommitFailedException();
        }
      }
      else {
        // Attempt to release this savepoint in the standard way.
        try {
          $this->query('RELEASE SAVEPOINT ' . $name);
        }
        catch (PDOException $e) {
          // However, in MySQL (InnoDB), savepoints are automatically committed
          // when tables are altered or created (DDL transactions are not
          // supported). This can cause exceptions due to trying to release
          // savepoints which no longer exist.
          //
          // To avoid exceptions when no actual error has occurred, we silently
          // succeed for MySQL error code 1305 ("SAVEPOINT does not exist").
          if ($e->errorInfo[1] == '1305') {
            // If one SAVEPOINT was released automatically, then all were.
            // Therefore, clean the transaction stack.
            $this->transactionLayers = array();
            // We also have to explain to PDO that the transaction stack has
            // been cleaned-up.
            PDO::commit();
          }
          else {
            throw $e;
          }
        }
      }
    }
  }

  public function utf8mb4IsConfigurable() {
    return TRUE;
  }

  public function utf8mb4IsActive() {
    return isset($this->connectionOptions['charset']) && $this->connectionOptions['charset'] === 'utf8mb4';
  }

  public function utf8mb4IsSupported() {
    // Ensure that the MySQL driver supports utf8mb4 encoding.
    $version = $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
    if (strpos($version, 'mysqlnd') !== FALSE) {
      // The mysqlnd driver supports utf8mb4 starting at version 5.0.9.
      $version = preg_replace('/^\D+([\d.]+).*/', '$1', $version);
      if (version_compare($version, '5.0.9', '<')) {
        return FALSE;
      }
    }
    else {
      // The libmysqlclient driver supports utf8mb4 starting at version 5.5.3.
      if (version_compare($version, '5.5.3', '<')) {
        return FALSE;
      }
    }

    // Ensure that the MySQL server supports large prefixes and utf8mb4.
    try {
      $this->query("CREATE TABLE {drupal_utf8mb4_test} (id VARCHAR(255), PRIMARY KEY(id(255))) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ROW_FORMAT=DYNAMIC ENGINE=INNODB");
    }
    catch (Exception $e) {
      return FALSE;
    }
    $this->query("DROP TABLE {drupal_utf8mb4_test}");
    return TRUE;
  }
}

/**
 * @} End of "addtogroup database".
 */