How to optimize WordPress with Ubuntu VPS

Ubuntu Virtual Private Server optimized for WordPress

Category: Apache config

Apache config

  • How to backup the Apache config file

    UpdraftPlus and other WP backup solution’s safeguards the work you have performed in WordPress. The Apache configuration files are left out. When disaster strikes, access to the Apache config files is invaluable. This might save you hours and perhaps days of downtime and frustration.

     

    Automate the process

    Below is the command listed one by one.
    A shell script that runs once a month from Cron would automate this.
    With TextExpander could you run this command sequence from your PC, Mac, iPhone and iPad as a snippet. To distinguish and automatically sort the backups the folders and filenames start with today’s date in the form: year-month-day

     

    Save the backup files in a single folder

    Create a folder you can access with SFTP and SCP. Then it’s easier to move the backup offsite. Either to your PC or another server or service. If you also choose to keep a local backup on the WP-JeOS server remember to change permissions on the file and folders. The bad guys would just love access to your SSL-certificates!

    cd /home/ubuntu/
    mkdir 20160627-backup-wp-jeos
    cd 20160627-backup-wp-jeos

    Now we are ready to start the work creating a backup of the Apache config files.

    Backing up SSL certificates

    Create a backup of the certificates

    sudo zip -r 20160627-etc-ssl-certs-.zip /etc/ssl/certs/*.*

    Create a backup of the private certificates
    First become root

    sudo su

    Then create the zip file:

    sudo zip -r 20160627-etc-ssl-private-.zip /etc/ssl/private/*.*

    Go back to the user ubuntu

    exit

     

    Backing up Apache main config file

    You have appropriately modified the main Apache config file to make the .htacces file work correctly.

    sudo zip 20160627-etc-apache2-apache2-conf.zip /etc/apache2/apache2.conf

    Backing up the virtual hosts config files

    The virtual hosts configuration files for each and every WordPress site might take much work to re-create when disaster strikes. A backup is a real time saver. The .conf file contains the path to your SSL-certificates, specifies the filename of your error logs and access logs and info about the root folder of WordPress.

    sudo zip -r 20160627-etc-apache2-sites-available-.zip /etc/apache2/sites-available/*.*

    Backup of the Apache config files completed. Now create a TextExpander snippet and perhaps a batch job to perform this fast next time you modify them. A cron job based on the bash script would further automate.

    Manually backing up WP-JeOS

    When you are at it, backing up the rest of WP-JeOs is easy. Sometimes backups are un-restorable. It could be many reasons for that. Having backups created with different solutions could be wise.

    Backing up the file structure

    When you have many websites creating a zip-file of the structure is done with this command. Beware. The zip-file could end up to being massive.

    sudo zip -r 20160627-var-www-.zip /var/www/

    A real timesaver when you need to migrate the whole server. It would usually take less time than restoring one site at a time with UpdraftPlus. Keep in mind that WP-CLI and WordShell are great tools when migrating, creating backups and restoring. WordShell has an excellent integrated backup solution.

    Backing up databases

    Since we run Amazon RDS MySQL, backup of the databases is less critical. Amazon automatically creates database backups for you. Use the RDS control panel to configures database backups. Modify to fit your needs. Eventually, the RDS backups are overwritten. If it takes months to the problem, corruption or whatever goes wrong is detected. Then a local offsite backup is the only thing that can come to your rescue. Creating backups with free software is easy. Try these:

    • MySQL Workbench
    • Sequel Pro
    • Navicat

     

     

    Move the backup offsite

    Backup files on a server that you can not access are worthless. Copy or move the backup offsite to another server or service like DropBox, Google Drive or Amazon S3.  You never know what’s ahead.

    Verify the backup

    Download the backup to your PC. Unzip the files to verify that the zip files contains the intended content.

    Restore to a local VPS

    VmWare is a great tool. Test that you can regenerate the server to a new VPS running on your PC. VmWare is a user-friendly tool for running Ubuntu on you local workstation. Restoring backups requires practice. It could occur that you are unable to restore a backup. The backup might be incomplete or corrupt. You could run into unforeseen problems when restoring backups. There might be a 3. party plugins or locked software that requires a particular IP to work. Certificates that is locked to a certain environment. It could be many obstacles occurring that you could not foresee or has forgotten. Usually, disaster recovery is a very stressful situation that in the long term is damaging to your health. Practice enables you to perform migration faster and with less wear and tear on your health.

    Protect the backup

    If you keep backups on the WP-JeOs, then you should change the permissions to the files and folders. The backup contains your passwords, SSL-certs and lots of valuable stuff that the bad guys just would love to access.

  • Tune apache performance using Apache MPM prefork module

    Tune apache performance using Apache MPM prefork module

    There could be many reasons why your Apache web server is slow. One of them can be that Apache needs tuning. Tuning the Apache performance using the Apache MPM prefork module is one of them.

    Tune Apache performance using MPM Prefork module

    StartServers: 30% of MaxClients
    MinSpareServers: 5% of MaxClients
    MaxSpareServers: 10% of MaxClients
    MaxRequestWorkers = MaxClients
    MaxConnectionsPerChild= 10000 (To avoid problem with memory leaks in WordPress plugin themes and apps)

     
    Edit the file with this command:

    sudo nano /etc/apache2/mods-available/mpm_prefork.conf

     

    Try these values if Apache uses 70 MB under heavy load and the server has 1 GB RAM.

    <IfModule mpm_prefork_module>
     StartServers 8
     MinSpareServers 8
     MaxSpareServers 9
     MaxRequestWorkers 9
     MaxConnectionsPerChild 100
    </IfModule>
    

    Save the changes

    Ctrl+X - Y

    Restart Apache

    sudo service apache2 restart

    It might make the server a bit slower, but there will be the most available memory, and you will not hit the roof. Hitting the limit will almost stop the server.

    How to calculate the values

    The initial  Ubuntu OS install uses 350 MB RAM – memory – and the server has 1 GB with memory.

    Then there is half a gigabyte to run Apache clients.

    You measure that each Apache instance uses 33 MB of memory. Then you would be able to run 18 servers with 650 MB available RAM. 650 MB RAM allows ten customers to download content from your site simultaneously. Often the browser uses several simultaneous instances so one user could use several Apache instances. Upgrade to 4 GB of RAM then you would have 3.5 GB available to serve your customers with Apache. 3,5 GB of available memory would suggest a “MaxClients” settings increased from ten clients to 106.

     

    Tool nr 1 to help you determine a useful configuration

    Check Apache Httpd MPM Config Limits

    This Perl script compares the size of running Apache HTTP processes. This consist of the configured Prefork, worker and event MPM limits. Measured towards the server’s available memory. You might get an error message if the setting limits exceed the server’s available memory.

    Check the website for the newest release.

    https://code.google.com/archive/p/check-httpd-limits/downloads

    Go to the user home folder

    cd ~

    Create a folder

    mkdir apache-memory-test

    Go to the newly created folder

    cd apache-memory-test

    Download the latest version. This is for version 2.5:

    wget https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/check-httpd-limits/check_httpd_limits-2.5.zip

    Unzip the file

    unzip check_httpd_limits-2.5.zip

    Make the script executable:

    chmod u+x check_httpd_limits.pl

    Run the script as root

    sudo ./check_httpd_limits.pl

    Open a bunch of web pages while you run the script many times to get an impression of the average memory consumed.

     

    Tool number 2

    Please read this tutorial about oApache” performance using optimizing MPM Prefork module

     

    Create a folder and download and unzip the script as you did with “Tool 1”

    Make the script executable

    chmod u+x ap.sh

    Run the script

    ./ap.sh

     

    Sources for this article

  • How to automatically restart apache every day, week or month

    How to automatically restart apache every day, week or month

    Your server might be more stable if you restart the apache service once a day, once a week or once a month. You can do this by adding a single line of text in the «Cron» service on your apache server.

     

    300x300-apache

     

    This command restarts the Apache service every morning 04:00 AM. That’s properly when there are few visitors. Takes a few seconds and properly is the users not noticing the downtime.

     

    Start Cron. First time you run this command you will probably be asked which text editor you want to use. I recommend that you choose Nano.

    sudo crontab -e

    In the text editor Nano, just add the following line. Then save and close the text editor Nano. That’s all

    0 4 * * 4 root service apache2 restart > /dev/null 2>&1

    This command will restart apache at 4 in the morning every Thursday.

    To check if this work use the command:

    sudo service apache2 status
  • How to install Apache, PHP7 and MySQL connector

    Setting up your MySQL database on Amazon RDS

    Use the free MySQL WorkBench to create your database, create database user, password and assign rights on Amazon RDS.

    Alternatively use Sequel Pro or use Navicat to set up your database on the  Amazon RDS database server. It dos not matter which of the 3 tools you are using.

    Install Apache2, PHP7, Curl and MySQL connector on Ubuntu

    This will install:

    • Apache
    • PHP7
    • MySQL database connector to access Amazon RDS. You will need this connector use the remote Amazon AWS RDS server.
    sudo apt-get install apache2 php7.0 php7.0-mysql libapache2-mod-php

    Install curl, gd and zip

    • Curl is widly used and needed by WordShell.
    • GD is needed by WordPress to change the size of uploaded images.
    • Zip is a easy way to compress directories and files when backing up or moving files and directories.
    sudo apt-get install curl php7.0-curl php7.0-gd zip

    Apache modules to activate

    sudo a2enmod rewrite

    Then restart Apache to activate the change:

    sudo service apache2 restart

     

  • Add virtual host and domains using a single IP

    The first IP address is free with Amazon AWS. Extra IP’s are not. This how-to guides you through the process of setting up as many virtual host domain in Apache as you need on a single IP. All WordPress sites using SSL / httpS://.

    Sites without SSL / httpS:// is given a lower SEO ranking by Google

    We have blocked port 80 in the firewall. All sites are using port 443 with a valid SSL certificate provided by CloudFlare. The only port open in the firewall is 22 for SSH admin and 443 for the hosts. SEO ranking for non-SSL sites are lower on Google.com. Since valid  SSL certificates are free. Who would create a site without encryption?

    Make sure Apache is configured correct for SSL and virtual host

    Ubuntu is not SSL prepared by default. Especially not for using many SSL sites on the same IP.  We will walk you through the needed modifications here:

     

    [themedy_button url=”https://www.wpjeos.no/enable-ssl-on-apache-ubuntu/” icon=”wrench” font_awesome_att=”” label=”How to configure Apache for SSL with virtual hosts on a single IP” colour=”blue” colour_custom=”” size=”large” edge=”rounded” target=”_self”]

     

    [themedy_button url=”https://www.wpjeos.no/adding-ssl-certificate-cloudflare/” icon=”adjust” font_awesome_att=”” label=”Adding SSL certificate from CloudFlare” colour=”blue” colour_custom=”” size=”large” edge=”rounded” target=”_self”]

    Create root folders to store your content

    First you need to create the website route folders on the file system where the files is to be stored.

    cd /var/www/
    sudo mkdir /var/www/MyDomain1.com
    sudo mkdir /var/www/MyDomain2.com
    sudo mkdir /var/www/MyDomain3.com

    Create a test file to use when verifying that the hosting works.

    sudo nano /var/www/MyDomain1.com/index.html

    Write:

    This is a test page for the domain https://www.mydomain1.com and/or https://mydomain1.com

    Save the file and exit Nano.

    Then make sure Apache can access these folders:

    chown -R www-data /var/www/
    
    

    Create the first site and use it as a template

    To add new domains to your configuration is a quite easy task on Apache.

    You just go to the folder where you find your existing config files.

    cd /etc/apache2/sites-available

    Then add a new config file for the new domain. Some times it’s easier to just copy an existing config file and edit it to reflect the name of the domain. To make it easier to troubleshoot problems it is a good habit to give each config file a number. This is because Apache will start one host at a time based on the number sequence.

    01-MyDomain1-com.conf
    02-MyDomain2-com.conf
    03-MyDomain3-com.conf
    

    To copy and the modifying an existing Apache configuration file

    Stop all the active config files and running Apache hosts.

    cd /etc/apache2/sites-available
    sudo a2dissite *.conf

    Then restart Apache so the changes takes effect

    sudo service apache2 restart

    First backup the default config files:

    sudo zip default-apache-config-files.zip *.conf

    Move the backup to your home folder:

    sudo mv zip default-apache-config-files.zip /home/ubuntu/default-apache-config-files.zip

    You might want to remove the non-SSL config file to keep the folder orderly:

     sudo rm 000-default.conf

    Now rename the default ssl config file

    sudo mv default-ssl.conf 01-MyDomain1-com.conf

    Finally we will modify the the configuration file:

    sudo nano 01-MyDomain1-com.conf

    This is what the Apache config file looks like before you start editing:

    <ifmodule mod_ssl.c>
     <virtualhost _default_:443>
     ServerAdmin mail@locahost
    
     DocumentRoot /var/www/html
    
     # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
     # error, crit, alert, emerg.
     # It is also possible to configure the loglevel for particular
     # modules, e.g.
     #LogLevel info ssl:warn
    
     ErrorLog ${APACHE_LOG_DIR}/error-default-.log
     CustomLog ${APACHE_LOG_DIR}/access-default-.log combined
    
    

    Modify the values in the file to look like this:

    <IfModule mod_ssl.c>
    <VirtualHost *:443>
    ServerAdmin mail@mydomain1.com
    ServerName mydomain1.com
    ServerAlias mydomain1.com
    DocumentRoot /var/www/MyDomain1.com ErrorLog ${APACHE_LOG_DIR}/01-mydomain1-com-error.log CustomLog ${APACHE_LOG_DIR}/01-mydomain1-com-access.log combined 

    Save the file.
    Activate the config file:

    sudo a2ensite 01-MyDomain1-com.conf

    Restart Apache

    sudo service apache2 restart

    GoCheck that the configuration file is correct with these tools:

    sudo apachectl configtest
    
    sudo systemctl status apache2.service
    
    sudo journalctl -xe
    
    

    Start a web browser and go to https://mydomain1-com or https://www.mydomain1-com to verify that you can access the page you created earlier with the text:

    This is a test page for the domain https://www.mydomain1.com and/or https://mydomain1.com

    If this page is not displayed, you should not continue before the error is solved. Continueing will make the troubleshooting more complex.

    Continuing with the 2. and 3. domain / virtual host

    Now use 01-MyDomain1-com.conf as the template for the two next virtual hosts.

    To copy an existing file:

    sudo cp 01-MyDomain1-com.conf 02-MyDomain2-com.conf
    
    sudo nano 02-MyDomain2-com.conf

    Then edit the config to match the second WordPress site:

    <IfModule mod_ssl.c>
    <VirtualHost *:443>
    ServerAdmin mail@mydomain2.com
    ServerName mydomain2.com
    ServerAlias mydomain2.com
    DocumentRoot /var/www/MyDomain2.com
    ErrorLog ${APACHE_LOG_DIR}/02-mydomain2-com-error.log
    CustomLog ${APACHE_LOG_DIR}/02-mydomain2-com-access.log combined
    
    
    Save.
    Then activate the configuration.
    
    sudo a2ensite *.conf

    Finally restart Apache so the new site gets published.

    sudo service apache2 restart

    Check and verify that the new site are online.

    Now repeat the process above to create the 3. WordPress site:

    sudo cp 01-MyDomain1-com.conf 03-MyDomain3-com.conf

    Then edit the config file

    sudo nano 03-MyDomain3-com.conf

    Change the values so it looks like this:

    <IfModule mod_ssl.c>
    <VirtualHost *:443>
    ServerAdmin mail@mydomain3.com
    ServerName mydomain3.com
    ServerAlias mydomain3.com
    DocumentRoot /var/www/MyDomain3.com ErrorLog ${APACHE_LOG_DIR}/03-mydomain3-com-error.log CustomLog ${APACHE_LOG_DIR}/03-mydomain3-com-access.log combined
    

    Save.
    Then activate the configuration.

    sudo a2ensite *.conf

    Finally restart Apache so the new site gets published.

    sudo service apache2 restart

    Check that the Apache config file is correct:

    sudo apachectl configtest
    
    sudo systemctl status apache2.service
    
    sudo journalctl -xe
    

    When troubleshooting then, disable, enable and activate Apache domain config files with these commands:

    sudo a2ensite *.conf
    
    sudo a2dissite *.conf
    
    sudo service apache2 restart
    

     

    Check and verify that the new site is online.

    Check the server error logs

    It’s a good practice to check the error logs. They are here:

    cd /var/log/apache2/
    sudo nano error.log
    sudo nano 01-mydomain1-com-error.log
    sudo nano 02-mydomain2-com-error.log
    sudo nano 03-mydomain3-com-error.log

    Set correct permissions so Apache can access

    sudo chown -R www-data /etc/apache2/sites-enabled
    sudo chown -R www-data /var/www/MyDomain1.com