Automating WordPress Installation with NGINX Unit and Ubuntu

Automating WordPress Installation with NGINX Unit and Ubuntu

There are many materials on installing WordPress, a Google search for the keywords "WordPress install" will yield around half a million results. However, among them, there are very few decent guides that enable you to install and configure WordPress and the underlying operating system for long-term support. It is possible that the correct settings depend heavily on specific needs, or it could be that detailed explanations make the articles difficult to read.

In this article, we will attempt to combine the best of both approaches by providing a bash script for the automatic installation of WordPress on Ubuntu, while also explaining each part of it, including the compromises we made during its development. If you are an experienced user, you may skip the text of the article and simply take the script for modification and use in your environments. The output of the script results in a customizable WordPress installation with Lets Encrypt support, operating on NGINX Unit and suitable for production use.

The architecture designed for deploying WordPress using NGINX Unit is described in an older article, and now we will also fine-tune aspects that were not covered there (as well as in many other guides):

  • WordPress CLI
  • Let’s Encrypt and TLS certificates
  • Automatic certificate renewal
  • NGINX caching
  • NGINX compression
  • Support for HTTPS and HTTP/2
  • Process automation

The article will describe the installation on a single server, which will simultaneously host a static files server, a PHP processing server, and a database. Installation with support for multiple virtual hosts and services is a potential topic for the future. If you want us to write about something not covered in these articles, please leave a comment.

Requirements

  • A container server (LXC or LXD), a virtual machine, or a physical server, with at least 512 MB of RAM and Ubuntu 18.04 or newer installed.
  • Ports 80 and 443 accessible from the internet
  • A domain name associated with the public IP address of this server
  • Access with root permissions (sudo).

Architecture Overview

The architecture is the same as described earlier, a three-tier web application. It consists of PHP scripts executed on a PHP handler and static files processed by a web server.

Automating WordPress Installation with NGINX Unit and Ubuntu

General Principles

  • Many configuration commands in the script are wrapped in conditions (if) for idempotency: the script can be run multiple times without the risk of altering settings that are already prepared.
  • The script tries to install software from repositories, so you can apply system updates in one command (apt upgrade for Ubuntu).
  • The commands attempt to identify if they are running in a container to adjust their configurations accordingly.
  • To specify the number of processes/threads to run in the settings, the script tries to guess automatic settings parameters for working in containers, virtual machines, and physical servers.
  • When describing configurations, we always think first about automation, which we hope will become the foundation for creating your own infrastructure as code.
  • All commands run as the user root, because they alter critical system settings, but WordPress itself operates as a regular user.

Setting Environment Variables

Set the following environment variables before running the script:

  • WORDPRESS_DB_PASSWORD — the password for the WordPress database
  • WORDPRESS_ADMIN_USER — the WordPress admin username
  • WORDPRESS_ADMIN_PASSWORD — the WordPress admin password
  • WORDPRESS_ADMIN_EMAIL — the WordPress admin email
  • WORDPRESS_URL — the full URL of the WordPress site, starting with https://.
  • LETS_ENCRYPT_STAGING — empty by default, but setting the value to 1 will use Let’s Encrypt staging servers, necessary for frequent certificate requests when testing your settings, otherwise Let’s Encrypt may temporarily block your IP address due to a high number of requests.

The script checks that these WordPress-related variables are set, and terminates if they are not.
Lines 572-576 of the script verify the values. LETS_ENCRYPT_STAGING.

Setting Derived Environment Variables

The script in lines 55-61 sets the following environment variables, either to hardcoded values or using values obtained from the variables set in the previous section:

  • DEBIAN_FRONTEND="noninteractive" — informs applications that they are running in a script and there is no possibility of user interaction.
  • WORDPRESS_CLI_VERSION="2.4.0" — version of the WordPress CLI application.
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" — checksum of the WordPress CLI 2.4.0 executable file (the version is specified in the variable WORDPRESS_CLI_VERSION). The script on line 162 uses this value to verify that the correct WordPress CLI file has been downloaded.
  • UPLOAD_MAX_FILESIZE="16M" — maximum file size that can be uploaded to WordPress. This setting is used in several places, so it is easier to set it in one place.
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'\/ -f3)" — the hostname of the system, extracted from the WORDPRESS_URL variable. Used to retrieve the corresponding TLS/SSL certificates from Let’s Encrypt, as well as for internal WordPress verification.
  • NGINX_CONF_DIR="\/etc\/nginx" — path to the directory with NGINX settings, including the main file nginx.conf.
  • CERT_DIR="\/etc\/letsencrypt\/live\/${TLS_HOSTNAME}" — path to the Let’s Encrypt certificates for the WordPress site, obtained from the variable TLS_HOSTNAME.

Assigning hostname to the WordPress server

The script sets the hostname for the server so that the value matches the domain name of the site. This is not mandatory, but it's easier to send outgoing mail through SMTP when configuring a single server, as set up by the script.

script code

# Change the hostname to be the same as the WordPress hostname
if [ ! "$(hostname)" == "${TLS_HOSTNAME}" ]; then
  echo " Changing hostname to ${TLS_HOSTNAME}"
  hostnamectl set-hostname "${TLS_HOSTNAME}"
fi

Adding hostname to /etc/hosts

Supplement WP‑Cron is used to run scheduled tasks, and requires that WordPress can access itself via HTTP. To ensure that WP-Cron works correctly in all environments, the script adds a line to the file /etc/hosts, so WordPress can access itself through the loopback interface:

script code

# Add the hostname to /etc/hosts
if [ "$(grep -m1 "${TLS_HOSTNAME}" /etc/hosts)" = "" ]; then
  echo " Adding hostname ${TLS_HOSTNAME} to /etc/hosts so that WordPress can ping itself"
  printf "::1 %sn127.0.0.1 %sn" "${TLS_HOSTNAME}" "${TLS_HOSTNAME}" >> /etc/hosts
fi

Installing tools required for subsequent steps

The remaining part of the script requires some programs and assumes that the repositories are up to date. We update the list of repositories, after which we install the necessary tools:

script code

# Make sure tools needed for install are present
echo " Installing prerequisite tools"
apt-get -qq update
apt-get -qq install -y 
  bc 
  ca-certificates 
  coreutils 
  curl 
  gnupg2 
  lsb-release

Adding NGINX Unit and NGINX repositories

The script installs NGINX Unit and NGINX from the official NGINX repositories to ensure that the versions with the latest security updates and bug fixes are used.

The script adds the NGINX Unit repository and then the NGINX repository, adding the repository keys and configuration files apt, defining access to the repositories over the internet.

The actual installation of NGINX Unit and NGINX occurs in the following section. We pre-add repositories to avoid updating metadata multiple times, which speeds up the installation.

script code

# Install the NGINX Unit repository
if [ ! -f /etc/apt/sources.list.d/unit.list ]; then
  echo " Installing NGINX Unit repository"
  curl -fsSL https://nginx.org/keys/nginx_signing.key | apt-key add -
  echo "deb https://packages.nginx.org/unit/ubuntu/ $(lsb_release -cs) unit" > /etc/apt/sources.list.d/unit.list
fi

# Install the NGINX repository
if [ ! -f /etc/apt/sources.list.d/nginx.list ]; then
  echo " Installing NGINX repository"
  curl -fsSL https://nginx.org/keys/nginx_signing.key | apt-key add -
  echo "deb https://nginx.org/packages/mainline/ubuntu $(lsb_release -cs) nginx" > /etc/apt/sources.list.d/nginx.list
fi

Installation of NGINX, NGINX Unit, PHP MariaDB, Certbot (Let’s Encrypt) and their dependencies

Once all repositories are added, we update the metadata and install the applications. The packages installed by the script also include PHP extensions recommended when running WordPress.org

script code

echo " Updating repository metadata"
apt-get -qq update

# Install PHP with dependencies and NGINX Unit
echo " Installing PHP, NGINX Unit, NGINX, Certbot, and MariaDB"
apt-get -qq install -y --no-install-recommends 
  certbot 
  python3-certbot-nginx 
  php-cli 
  php-common 
  php-bcmath 
  php-curl 
  php-gd 
  php-imagick 
  php-mbstring 
  php-mysql 
  php-opcache 
  php-xml 
  php-zip 
  ghostscript 
  nginx 
  unit 
  unit-php 
  mariadb-server

Configuring PHP for use with NGINX Unit and WordPress

The script creates a configuration file in the directory conf.d. Here, the maximum upload file size for PHP is set, error output for PHP is enabled to STDERR so they will be logged in NGINX Unit, and NGINX Unit is restarted.

script code

# Find the major and minor PHP version so that we can write to its conf.d directory
PHP_MAJOR_MINOR_VERSION="$(php -v | head -n1 | cut -d' ' -f2 | cut -d'.' -f1,2)"

if [ ! -f "/etc/php/${PHP_MAJOR_MINOR_VERSION}/embed/conf.d/30-wordpress-overrides.ini" ]; then
  echo " Configuring PHP for use with NGINX Unit and WordPress"
  # Add PHP configuration overrides
  cat > "/etc/php/${PHP_MAJOR_MINOR_VERSION}/embed/conf.d/30-wordpress-overrides.ini" << EOM
; Set a larger maximum upload size so that WordPress can handle
; bigger media files.
upload_max_filesize=${UPLOAD_MAX_FILESIZE}
post_max_size=${UPLOAD_MAX_FILESIZE}
; Write error log to STDERR so that error messages show up in the NGINX Unit log
error_log=/dev/stderr
EOM
fi

# Restart NGINX Unit because we have reconfigured PHP
echo " Restarting NGINX Unit"
service unit restart

Setting up database configurations for MariaDB for WordPress

We chose MariaDB over MySQL as it has more community involvement, in addition, it may provide higher performance by default (likely makes things simpler: to install MySQL, you need to add another repository, (translator's note).

The script creates a new database and sets up access credentials for WordPress via the loopback interface:

script code

# Set up the WordPress database
echo " Configuring MariaDB for WordPress"
mysqladmin create wordpress || echo "Ignoring above error because database may already exist"
mysql -e "GRANT ALL PRIVILEGES ON wordpress.* TO "wordpress"@"localhost" IDENTIFIED BY "$WORDPRESS_DB_PASSWORD"; FLUSH PRIVILEGES;"

Installing WordPress CLI

At this step, the script installs the WP-CLI. It allows you to install and manage WordPress settings without the need to manually edit files, update the database, or log into the control panel. It can also be used to install themes and plugins and perform WordPress updates.

script code

if [ ! -f /usr/local/bin/wp ]; then
  # Install the WordPress CLI
  echo " Installing the WordPress CLI tool"
  curl --retry 6 -Ls "https://github.com/wp-cli/wp-cli/releases/download/v${WORDPRESS_CLI_VERSION}/wp-cli-${WORDPRESS_CLI_VERSION}.phar" > /usr/local/bin/wp
  echo "$WORDPRESS_CLI_MD5 /usr/local/bin/wp" | md5sum -c -
  chmod +x /usr/local/bin/wp
fi

Installing and configuring WordPress

The script installs the latest version of WordPress in the directory /var/www/wordpress, and also changes the settings:

  • The connection to the database works through a unix domain socket instead of TCP on the loopback to reduce TCP traffic.
  • WordPress adds a prefix https:// to the URL, if clients connect to NGINX via the HTTPS protocol, and also sends the remote hostname (as provided by NGINX) to PHP. We use a snippet of code to set this up.
  • WordPress requires HTTPS for login.
  • The URL structure is based on the resources by default.
  • The correct permissions are set on the file system for the WordPress directory.

script code

if [ ! -d /var/www/wordpress ]; then
  # Create WordPress directories
  mkdir -p /var/www/wordpress
  chown -R www-data:www-data /var/www

  # Download WordPress using the WordPress CLI
  echo " Installing WordPress"
  su -s /bin/sh -c 'wp --path=/var/www/wordpress core download' www-data

  WP_CONFIG_CREATE_CMD="wp --path=/var/www/wordpress config create --extra-php --dbname=wordpress --dbuser=wordpress --dbhost='localhost:/var/run/mysqld/mysqld.sock' --dbpass='${WORDPRESS_DB_PASSWORD}'"

  # This snippet is injected into the wp-config.php file when it is created;
  # it informs WordPress that we are behind a reverse proxy and as such
  # allows it to generate links using HTTPS
  cat > /tmp/wp_forwarded_for.php << 'EOM'
/* Turn HTTPS 'on' if HTTP_X_FORWARDED_PROTO matches 'https' */
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) {
    $_SERVER['HTTPS'] = 'on';
}
if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
    $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
}
EOM

  # Create WordPress configuration
  su -s /bin/sh -p -c "cat /tmp/wp_forwarded_for.php | ${WP_CONFIG_CREATE_CMD}" www-data
  rm /tmp/wp_forwarded_for.php
  su -s /bin/sh -p -c "wp --path=/var/www/wordpress config set 'FORCE_SSL_ADMIN' 'true'" www-data

  # Install WordPress
  WP_SITE_INSTALL_CMD="wp --path=/var/www/wordpress core install --url='${WORDPRESS_URL}' --title='${WORDPRESS_SITE_TITLE}' --admin_user='${WORDPRESS_ADMIN_USER}' --admin_password='${WORDPRESS_ADMIN_PASSWORD}' --admin_email='${WORDPRESS_ADMIN_EMAIL}' --skip-email"
  su -s /bin/sh -p -c "${WP_SITE_INSTALL_CMD}" www-data

  # Set permalink structure to a sensible default that isn't in the UI
  su -s /bin/sh -p -c "wp --path=/var/www/wordpress option update permalink_structure '/%year%/%monthnum%/%postname%/'" www-data

  # Remove sample file because it is cruft and could be a security problem
  rm /var/www/wordpress/wp-config-sample.php

  # Ensure that WordPress permissions are correct
  find /var/www/wordpress -type d -exec chmod g+s {} ;
  chmod g+w /var/www/wordpress/wp-content
  chmod -R g+w /var/www/wordpress/wp-content/themes
  chmod -R g+w /var/www/wordpress/wp-content/plugins
fi

Configuring NGINX Unit

The script configures NGINX Unit to run PHP and handle WordPress paths, isolating the PHP process namespace and optimizing performance settings. There are three functions worth noting here:

  • Namespace support is determined by a condition based on checking whether the script is running in a container. This is necessary since most container settings do not support nested container execution.
  • If namespace support is enabled, the namespace is disabled network. This is needed to allow WordPress to connect to both endpoints and be accessible on the internet.
  • The maximum number of processes is determined as follows: (Available memory for running MariaDB and NGINX Unit)/(limit on PHP memory + 5)
    This value is set in the NGINX Unit settings.

This value also implies that there are always at least two PHP processes running, which is important because WordPress makes many asynchronous calls to itself, and without additional processes, the execution of WP-Cron, for example, will break. You may want to increase or decrease these limits based on your local settings, as the settings created here are conservative. On most production systems, the settings range from 10 to 100.

script code

if [ "${container:-unknown}" != "lxc" ] && [ "$(grep -m1 -a container=lxc /proc/1/environ | tr -d ' ')" == "" ]; then
  NAMESPACES='"namespaces": {
        "cgroup": true,
        "credential": true,
        "mount": true,
        "network": false,
        "pid": true,
        "uname": true
    }'
else
  NAMESPACES='"namespaces": {}'
fi

PHP_MEM_LIMIT="$(grep 'memory_limit' /etc/php/7.4/embed/php.ini | tr -d ' ' | cut -f2 -d= | numfmt --from=iec)"
AVAIL_MEM="$(grep MemAvailable /proc/meminfo | tr -d ' kB' | cut -f2 -d: | numfmt --from-unit=K)"
MAX_PHP_PROCESSES="$(echo "${AVAIL_MEM}/${PHP_MEM_LIMIT}+5" | bc)"
echo " Calculated the maximum number of PHP processes as ${MAX_PHP_PROCESSES}. You may want to tune this value due to variations in your configuration. It is not unusual to see values between 10-100 in production configurations."

echo " Configuring NGINX Unit to use PHP and WordPress"
cat > /tmp/wordpress.json << EOM
{
  "settings": {
    "http": {
      "header_read_timeout": 30,
      "body_read_timeout": 30,
      "send_timeout": 30,
      "idle_timeout": 180,
      "max_body_size": $(numfmt --from=iec ${UPLOAD_MAX_FILESIZE})
    }
  },
  "listeners": {
    "127.0.0.1:8080": {
      "pass": "routes/wordpress"
    }
  },
  "routes": {
    "wordpress": [
      {
        "match": {
          "uri": [
            "*.php",
            "*.php/*",
            "/wp-admin/"
          ]
        },
        "action": {
          "pass": "applications/wordpress/direct"
        }
      },
      {
        "action": {
          "share": "/var/www/wordpress",
          "fallback": {
            "pass": "applications/wordpress/index"
          }
        }
      }
    ]
  },
  "applications": {
    "wordpress": {
      "type": "php",
      "user": "www-data",
      "group": "www-data",
      "processes": {
        "max": ${MAX_PHP_PROCESSES},
        "spare": 1
      },
      "isolation": {
        ${NAMESPACES}
      },
      "targets": {
        "direct": {
          "root": "/var/www/wordpress/"
        },
        "index": {
          "root": "/var/www/wordpress/",
          "script": "index.php"
        }
      }
    }
  }
}
EOM

curl -X PUT --data-binary @/tmp/wordpress.json --unix-socket /run/control.unit.sock http://localhost/config

NGINX Configuration

Configuration of basic NGINX parameters

The script creates a directory for NGINX cache and then creates the main configuration file. nginx.confPlease pay attention to the number of worker processes and set a maximum file upload size. There is also a line that connects to the compression settings file defined in the next section, followed by caching settings.

script code

# Make directory for NGINX cache
mkdir -p /var/cache/nginx/proxy

echo " Configuring NGINX"
cat > ${NGINX_CONF_DIR}/nginx.conf << EOM
user nginx;
worker_processes auto;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       ${NGINX_CONF_DIR}/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    client_max_body_size ${UPLOAD_MAX_FILESIZE};
    keepalive_timeout  65;
    # gzip settings
    include ${NGINX_CONF_DIR}/gzip_compression.conf;
    # Cache settings
    proxy_cache_path /var/cache/nginx/proxy
        levels=1:2
        keys_zone=wp_cache:10m
        max_size=10g
        inactive=60m
        use_temp_path=off;
    include ${NGINX_CONF_DIR}/conf.d/*.conf;
}
EOM

NGINX Compression Settings

On-the-fly content compression before sending it to clients is an excellent way to improve website performance, but only if the compression is configured correctly. This section of the script is based on the settings. from here.

script code

cat > ${NGINX_CONF_DIR}/gzip_compression.conf << 'EOM'
# Credit: https://github.com/h5bp/server-configs-nginx/
# ----------------------------------------------------------------------
# | Compression                                                        |
# ----------------------------------------------------------------------
# https://nginx.org/en/docs/http/ngx_http_gzip_module.html
# Enable gzip compression.
# Default: off
gzip on;
# Compression level (1-9).
# 5 is a perfect compromise between size and CPU usage, offering about 75%
# reduction for most ASCII files (almost identical to level 9).
# Default: 1
gzip_comp_level 6;
# Don't compress anything that's already small and unlikely to shrink much if at
# all (the default is 20 bytes, which is bad as that usually leads to larger
# files after gzipping).
# Default: 20
gzip_min_length 256;
# Compress data even for clients that are connecting to us via proxies,
# identified by the "Via" header (required for CloudFront).
# Default: off
gzip_proxied any;
# Tell proxies to cache both the gzipped and regular version of a resource
# whenever the client's Accept-Encoding capabilities header varies;
# Avoids the issue where a non-gzip capable client (which is extremely rare
# today) would display gibberish if their proxy gave them the gzipped version.
# Default: off
gzip_vary on;
# Compress all output labeled with one of the following MIME-types.
# `text/html` is always compressed by gzip module.
# Default: text/html
gzip_types
  application/atom+xml
  application/geo+json
  application/javascript
  application/x-javascript
  application/json
  application/ld+json
  application/manifest+json
  application/rdf+xml
  application/rss+xml
  application/vnd.ms-fontobject
  application/wasm
  application/x-web-app-manifest+json
  application/xhtml+xml
  application/xml
  font/eot
  font/otf
  font/ttf
  image/bmp
  image/svg+xml
  text/cache-manifest
  text/calendar
  text/css
  text/javascript
  text/markdown
  text/plain
  text/xml
  text/vcard
  text/vnd.rim.location.xloc
  text/vtt
  text/x-component
  text/x-cross-domain-policy;
EOM

NGINX Configuration for WordPress

Next, the script creates a configuration file for WordPress. default.conf in the directory conf.dHere it is configured:

  • Activation of TLS certificates obtained from Let’s Encrypt via Certbot (its setup will be in the next section)
  • Setting TLS security parameters based on recommendations from Let’s Encrypt
  • Enabling caching of bypassed requests for 1 hour by default
  • Disabling access logging and error logging if the file is not found for two commonly requested files: favicon.ico and robots.txt
  • Restricting access to hidden files and certain files .php, to prevent unauthorized access or unintentional execution
  • Disabling access logging for static files and fonts
  • Setting the header Access-Control-Allow-Origin for font files
  • Adding routing for index.php and other static files.

script code

cat > ${NGINX_CONF_DIR}/conf.d/default.conf << EOM
upstream unit_php_upstream {
    server 127.0.0.1:8080;
    keepalive 32;
}
server {
    listen 80;
    listen [::]:80;
    # ACME-challenge used by Certbot for Let's Encrypt
    location ^~ /.well-known/acme-challenge/ {
      root /var/www/certbot;
    }
    location / {
      return 301 https://${TLS_HOSTNAME}$request_uri;
    }
}
server {
    listen      443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${TLS_HOSTNAME};
    root        /var/www/wordpress/;
    # Let's Encrypt configuration
    ssl_certificate         ${CERT_DIR}/fullchain.pem;
    ssl_certificate_key     ${CERT_DIR}/privkey.pem;
    ssl_trusted_certificate ${CERT_DIR}/chain.pem;
    include ${NGINX_CONF_DIR}/options-ssl-nginx.conf;
    ssl_dhparam ${NGINX_CONF_DIR}/ssl-dhparams.pem;
    # OCSP stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    # Proxy caching
    proxy_cache wp_cache;
    proxy_cache_valid 200 302 1h;
    proxy_cache_valid 404 1m;
    proxy_cache_revalidate on;
    proxy_cache_background_update on;
    proxy_cache_lock on;
    proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }
    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Deny all attempts to access hidden files such as .htaccess, .htpasswd,
    # .DS_Store (Mac)
    # Keep logging the requests to parse later (or to pass to firewall utilities
    # such as fail2ban)
    location ~ /.{
        deny all;
    }
    # Deny access to any files with a .php extension in the uploads directory;
    # works in subdirectory installs and also in multi-site network.
    # Keep logging the requests to parse later (or to pass to firewall utilities
    # such as fail2ban).
    location ~* /(?:uploads|files)/.*.php$ {
        deny all;
    }
    # WordPress: deny access to wp-content, wp-includes PHP files
    location ~* ^/(?:wp-content|wp-includes)/.*.php$ {
        deny all;
    }
    # Deny public access to wp-config.php
    location ~* wp-config.php {
        deny all;
    }
    # Do not log access for static assets, media
    location ~* .(?:css(.map)?|js(.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
        access_log off;
    }
    location ~* .(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
        add_header Access-Control-Allow-Origin "*";
        access_log off;
    }
    location / {
        try_files $uri @index_php;
    }
    location @index_php {
        proxy_socket_keepalive on;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $host;
        proxy_pass       http://unit_php_upstream;
    }
    location ~* .php$ {
        proxy_socket_keepalive on;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $host;
        try_files        $uri =404;
        proxy_pass       http://unit_php_upstream;
    }
}
EOM

Setting Up Certbot for Certificates from Let’s Encrypt and Their Automatic Renewal

Certbot is a free tool from the Electronic Frontier Foundation (EFF) that allows you to obtain and automatically renew TLS certificates from Let’s Encrypt. The script performs the following actions to set up Certbot for handling certificates from Let’s Encrypt in NGINX:

  • Stops NGINX
  • Downloads recommended TLS parameters
  • Launches Certbot to obtain certificates for the website
  • Restarts NGINX to use the certificates
  • Schedules daily execution of Certbot at 3:24 AM to check for the need to renew certificates, as well as, if necessary, download new certificates and restart NGINX.

script code

echo " Stopping NGINX in order to set up Let's Encrypt"
service nginx stop

mkdir -p /var/www/certbot
chown www-data:www-data /var/www/certbot
chmod g+s /var/www/certbot

if [ ! -f ${NGINX_CONF_DIR}/options-ssl-nginx.conf ]; then
  echo " Downloading recommended TLS parameters"
  curl --retry 6 -Ls -z "Tue, 14 Apr 2020 16:36:07 GMT" 
    -o "${NGINX_CONF_DIR}/options-ssl-nginx.conf" 
    "https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf" 
    || echo "Couldn't download latest options-ssl-nginx.conf"
fi

if [ ! -f ${NGINX_CONF_DIR}/ssl-dhparams.pem ]; then
  echo " Downloading recommended TLS DH parameters"
  curl --retry 6 -Ls -z "Tue, 14 Apr 2020 16:49:18 GMT" 
    -o "${NGINX_CONF_DIR}/ssl-dhparams.pem" 
    "https://raw.githubusercontent.com/certbot/certbot/master/certbot/certbot/ssl-dhparams.pem" 
    || echo "Couldn't download latest ssl-dhparams.pem"
fi

# If tls_certs_init.sh hasn't been run before, remove the self-signed certs
if [ ! -d "/etc/letsencrypt/accounts" ]; then
  echo " Removing self-signed certificates"
  rm -rf "${CERT_DIR}"
fi

if [ "" = "${LETS_ENCRYPT_STAGING:-}" ] || [ "0" = "${LETS_ENCRYPT_STAGING}" ]; then
  CERTBOT_STAGING_FLAG=""
else
  CERTBOT_STAGING_FLAG="--staging"
fi

if [ ! -f "${CERT_DIR}/fullchain.pem" ]; then
  echo " Generating certificates with Let's Encrypt"
  certbot certonly --standalone 
         -m "${WORDPRESS_ADMIN_EMAIL}" 
         ${CERTBOT_STAGING_FLAG} 
         --agree-tos --force-renewal --non-interactive 
         -d "${TLS_HOSTNAME}"
fi

echo " Starting NGINX in order to use new configuration"
service nginx start

# Write crontab for periodic Let's Encrypt cert renewal
if [ "$(crontab -l | grep -m1 'certbot renew')" == "" ]; then
  echo " Adding certbot to crontab for automatic Let's Encrypt renewal"
  (crontab -l 2>/dev/null; echo "24 3 * * * certbot renew --nginx --post-hook 'service nginx reload'") | crontab -
fi

Additional Configuration for Your Website

We have explained above how our script configures NGINX and NGINX Unit to serve a production-ready website with enabled TLSSSL. You may also, depending on your needs, add in the future:

  • Support Brotli., enhanced on-the-fly compression over HTTPS
  • ModSecurity with rules for WordPress, to prevent automated attacks on your website
  • Backup for WordPress that suits you
  • Protection using AppArmor (on Ubuntu)
  • Postfix or msmtp, so WordPress can send emails
  • Checks of your website to understand how much traffic it can handle

For even better site performance, we recommend upgrading to NGINX Plus, our enterprise-level commercial product based on open-source NGINX. Its subscribers will receive a dynamically loaded Brotli module, as well as (for an additional fee) NGINX ModSecurity WAF. We also offer NGINX App Protect, a WAF module for NGINX Plus, based on industry-leading security technology from F5.

N.B. For support with high-load websites, you can contact our specialists Southbridge. We ensure fast and reliable operation of your website or service under any load.

Source: habr.com

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster