Automating WordPress installation nrog NGINX Unit thiab Ubuntu

Automating WordPress installation nrog NGINX Unit thiab Ubuntu

Muaj ntau ntau cov lus qhia txog yuav ua li cas rau nruab WordPress, Google tshawb rau "WordPress install" yuav tig txog li ib nrab lab cov txiaj ntsig. Txawm li cas los xij, qhov tseeb, muaj ob peb cov lus qhia zoo ntawm lawv, raws li qhov koj tuaj yeem nruab thiab teeb tsa WordPress thiab lub hauv paus kev ua haujlwm kom lawv muaj peev xwm txhawb nqa lub sijhawm ntev. Tej zaum qhov kev teeb tsa raug yog nyob ntawm qhov xav tau tshwj xeeb, lossis qhov no yog vim qhov tseeb tias cov lus piav qhia ntxaws ua rau cov ntawv nyeem nyuaj.

Hauv tsab xov xwm no, peb yuav sim ua ke qhov zoo tshaj plaws ntawm ob lub ntiaj teb los ntawm kev muab tsab ntawv bash kom tau nruab WordPress ntawm Ubuntu, nrog rau taug kev los ntawm nws, piav qhia tias txhua daim ua dab tsi, nrog rau kev tsis txaus siab uas peb tau ua hauv kev tsim nws. . Yog tias koj yog ib tus neeg siv siab heev, koj tuaj yeem hla cov ntawv ntawm kab lus thiab tsuas yog coj tsab ntawv rau kev hloov kho thiab siv hauv koj qhov chaw ib puag ncig. Cov zis ntawm tsab ntawv yog kev cai WordPress installation nrog Lets Encrypt kev txhawb nqa, khiav ntawm NGINX Unit thiab tsim nyog rau kev siv ntau lawm.

Cov tsim qauv tsim rau kev siv WordPress siv NGINX Unit tau piav qhia hauv tsab ntawv qub, tam sim no peb tseem yuav ntxiv teeb tsa yam uas tsis tau them rau ntawd (raws li hauv ntau lwm yam kev qhia):

  • WordPress CLI
  • Cia Encrypt thiab TLSSSL Daim Ntawv Pov Thawj
  • Tsis siv neeg rov ua dua daim ntawv pov thawj
  • NGINX caching
  • NGINX Compression
  • HTTPS thiab HTTP/2 txhawb nqa
  • Txheej txheem automation

Kab lus yuav piav qhia txog kev teeb tsa ntawm ib tus neeg rau zaub mov, uas yuav ib txhij tuav lub server ua haujlwm zoo li qub, PHP ua haujlwm server, thiab database. Ib qho kev teeb tsa uas txhawb nqa ntau lub tuam txhab virtual thiab cov kev pabcuam yog lub ntsiab lus tseem ceeb rau yav tom ntej. Yog tias koj xav kom peb sau txog qee yam uas tsis yog hauv cov ntawv no, sau rau hauv cov lus.

uas yuav tsum tau

  • Container server (LXC los yog LXD), lub tshuab virtual, lossis cov neeg siv hlau tsis tu ncua nrog tsawg kawg 512MB ntawm RAM thiab Ubuntu 18.04 lossis tshiab dua.
  • Internet nkag tau ports 80 thiab 443
  • Lub npe lub npe cuam tshuam nrog pej xeem ip chaw nyob ntawm tus neeg rau zaub mov no
  • Root Access (sudo).

Architecture txheej txheem cej luam

Lub architecture zoo ib yam li tau piav qhia ua ntej lawm, peb-tier web application. Nws muaj PHP scripts uas khiav ntawm lub cav PHP thiab cov ntaub ntawv zoo li qub uas tau ua tiav los ntawm lub vev xaib server.

Automating WordPress installation nrog NGINX Unit thiab Ubuntu

Tej ntsiab cai

  • Ntau qhov kev teeb tsa cov lus txib hauv ib tsab ntawv yog qhwv hauv yog tias muaj xwm txheej rau idempotency: tsab ntawv tuaj yeem khiav ntau zaus yam tsis muaj kev pheej hmoo ntawm kev hloov chaw uas twb muaj lawm.
  • Tsab ntawv sim nruab software los ntawm repositories, yog li koj tuaj yeem siv cov kev hloov kho tshiab hauv ib qho lus txib (apt upgrade rau Ubuntu).
  • Cov lus txib sim kuaj xyuas tias lawv khiav hauv lub thawv kom lawv tuaj yeem hloov kho lawv qhov chaw raws li.
  • Txhawm rau teeb tsa cov xov tooj txheej txheem los pib hauv qhov chaw, tsab ntawv sim kwv yees qhov chaw tsis siv neeg ua haujlwm hauv ntim, tshuab virtual, thiab kho vajtse servers.
  • Thaum piav qhia txog kev teeb tsa, peb ib txwm xav ua ntej ntawm txhua yam ntawm automation, uas, peb cia siab tias, yuav dhau los ua lub hauv paus rau kev tsim koj tus kheej infrastructure raws li cov cai.
  • Tag nrho cov lus txib yog khiav raws li tus neeg siv hauv paus, vim hais tias lawv hloov cov kev teeb tsa yooj yim, tab sis ncaj qha WordPress khiav raws li cov neeg siv niaj hnub.

Teem ib puag ncig variables

Teem cov kev hloov pauv ib puag ncig hauv qab no ua ntej khiav tsab ntawv:

  • WORDPRESS_DB_PASSWORD - WordPress database password
  • WORDPRESS_ADMIN_USER - WordPress admin npe
  • WORDPRESS_ADMIN_PASSWORD - WordPress admin password
  • WORDPRESS_ADMIN_EMAIL - WordPress admin email
  • WORDPRESS_URL yog tag nrho URL ntawm lub vev xaib WordPress, pib ntawm https://.
  • LETS_ENCRYPT_STAGING - khoob los ntawm lub neej ntawd, tab sis los ntawm kev teeb tsa tus nqi rau 1, koj yuav siv Let's Encrypt staging servers, uas yog qhov tsim nyog rau nquag thov daim ntawv pov thawj thaum kuaj koj qhov chaw, txwv tsis pub Let's Encrypt tuaj yeem thaiv koj qhov chaw nyob ip ib ntus vim muaj ntau qhov kev thov. .

Tsab ntawv txheeb xyuas tias cov kev hloov pauv uas cuam tshuam nrog WordPress tau teeb tsa thiab tawm yog tsis yog.
Tsab ntawv kab 572-576 kos tus nqi LETS_ENCRYPT_STAGING.

Kev teeb tsa ib puag ncig hloov pauv

Tsab ntawv ntawm kab 55-61 teeb tsa cov kev hloov pauv ib puag ncig hauv qab no, xws li rau qee qhov nyuaj-coded tus nqi lossis siv tus nqi tau los ntawm qhov sib txawv tau teeb tsa hauv ntu dhau los:

  • DEBIAN_FRONTEND="noninteractive" - Qhia rau cov ntawv thov tias lawv tab tom khiav hauv tsab ntawv thiab tsis muaj kev cuam tshuam rau cov neeg siv.
  • WORDPRESS_CLI_VERSION="2.4.0" yog lub version ntawm WordPress CLI daim ntawv thov.
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" - checksum ntawm WordPress CLI 2.4.0 executable cov ntaub ntawv (tus version yog teev nyob rau hauv qhov sib txawv WORDPRESS_CLI_VERSION). Tsab ntawv ntawm kab 162 siv tus nqi no los xyuas tias qhov tseeb WordPress CLI cov ntaub ntawv tau raug rub tawm.
  • UPLOAD_MAX_FILESIZE="16M" - cov ntaub ntawv loj tshaj plaws uas tuaj yeem muab tso rau hauv WordPress. Qhov kev teeb tsa no tau siv ntau qhov chaw, yog li nws yooj yim dua los teeb tsa hauv ib qho chaw.
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)" - hostname ntawm lub kaw lus, muab los ntawm WORDPRESS_URL hloov pauv. Siv kom tau txais daim ntawv pov thawj TLS / SSL tsim nyog los ntawm Let's Encrypt nrog rau kev txheeb xyuas hauv WordPress.
  • NGINX_CONF_DIR="/etc/nginx" - txoj hauv kev mus rau cov npe nrog NGINX teeb tsa, suav nrog cov ntaub ntawv tseem ceeb nginx.conf.
  • CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}" - txoj kev mus rau Let's Encrypt daim ntawv pov thawj rau lub vev xaib WordPress, tau los ntawm qhov sib txawv TLS_HOSTNAME.

Muab lub hostname rau WordPress server

Tsab ntawv teev cov server lub hostname kom phim lub vev xaib lub npe. Qhov no tsis tas yuav tsum tau, tab sis nws yooj yim dua rau xa cov ntawv xa tawm ntawm SMTP thaum teeb tsa ib tus neeg rau zaub mov, raws li tau teeb tsa los ntawm tsab ntawv.

tsab ntawv 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

Ntxiv hostname rau /etc/hosts

Txuas ntxiv WP-Cron siv los ua haujlwm raws sijhawm, xav kom WordPress tuaj yeem nkag mus rau nws tus kheej ntawm HTTP. Txhawm rau kom paub tseeb tias WP-Cron ua haujlwm raug rau txhua qhov chaw, tsab ntawv ntxiv ib kab rau cov ntaub ntawv / etc / hostsyog li ntawd WordPress tuaj yeem nkag mus rau nws tus kheej ntawm lub loopback interface:

tsab ntawv 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

Txhim kho cov cuab yeej xav tau rau cov kauj ruam tom ntej

Tus so ntawm tsab ntawv xav tau qee qhov kev pab cuam thiab xav tias cov chaw khaws cia tau hloov tshiab. Peb hloov kho cov npe ntawm cov chaw cia khoom, tom qab ntawd peb nruab cov cuab yeej tsim nyog:

tsab ntawv 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

Ntxiv NGINX Chav thiab NGINX Repositories

Tsab ntawv teeb tsa NGINX Unit thiab qhib qhov chaw NGINX los ntawm official NGINX repositories kom paub tseeb tias cov versions nrog qhov tseeb kev ruaj ntseg thaj ua rau thaj thiab kho kab laum yog siv.

Tsab ntawv ntxiv NGINX Unit repository thiab ces NGINX repository, ntxiv cov repositories key thiab configuration ntaub ntawv apt, txhais kev nkag mus rau repositories ntawm Internet.

Qhov tseeb kev teeb tsa ntawm NGINX Unit thiab NGINX tshwm sim hauv ntu tom ntej. Peb pre-ntxiv cov repositories yog li peb tsis tas yuav hloov kho cov metadata ntau zaus, uas ua rau kev teeb tsa sai dua.

tsab ntawv 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

Txhim kho NGINX, NGINX Unit, PHP MariaDB, Certbot (Cia Encrypt) thiab lawv cov kev vam meej

Thaum tag nrho cov repositories ntxiv, hloov kho cov metadata thiab nruab cov ntawv thov. Cov pob khoom tau teeb tsa los ntawm tsab ntawv kuj suav nrog PHP txuas ntxiv pom zoo thaum khiav WordPress.org

tsab ntawv 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

Teeb tsa PHP siv nrog NGINX Unit thiab WordPress

Tsab ntawv tsim cov ntaub ntawv teeb tsa hauv cov npe conf.d. Qhov no teev cov ntaub ntawv loj tshaj plaws rau PHP uploads, tig rau PHP yuam kev tso tawm rau STDERR yog li lawv yuav raug sau rau NGINX Unit cav, thiab rov pib dua NGINX Unit.

tsab ntawv 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

Qhia meej MariaDB Database Chaw rau WordPress

Peb tau xaiv MariaDB dhau MySQL raws li nws muaj ntau lub zej zog kev ua ub no thiab kuj zoo li muab kev ua tau zoo dua los ntawm lub neej ntawd (Tej zaum, txhua yam yog yooj yim ntawm no: rau nruab MySQL, koj yuav tsum tau ntxiv lwm qhov chaw cia khoom, kwv yees. tus txhais lus).

Tsab ntawv tsim cov ntaub ntawv tshiab thiab tsim cov ntaub ntawv pov thawj nkag mus rau WordPress ntawm lub loopback interface:

tsab ntawv 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;"

Txhim kho WordPress CLI Program

Ntawm cov kauj ruam no, tsab ntawv nruab qhov program WP-CLI. Nrog nws, koj tuaj yeem nruab thiab tswj hwm WordPress chaw yam tsis tas yuav hloov kho cov ntaub ntawv manually, hloov kho cov ntaub ntawv, lossis nkag mus rau hauv pawg tswj hwm. Nws kuj tuaj yeem siv los nruab cov ntsiab lus thiab ntxiv-ons thiab hloov kho WordPress.

tsab ntawv 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

Txhim kho thiab teeb tsa WordPress

Tsab ntawv nruab qhov tseeb version ntawm WordPress hauv ib phau ntawv /var/www/wordpressthiab kuj hloov cov chaw:

  • Qhov kev sib txuas ntawm cov ntaub ntawv ua haujlwm dhau ntawm unix domain socket es tsis txhob TCP ntawm loopback los txiav tawm ntawm TCP tsheb.
  • WordPress ntxiv ua ntej https:// rau qhov URL yog tias cov neeg siv txuas rau NGINX dhau HTTPS, thiab tseem xa cov chaw taws teeb hostname (raws li muab los ntawm NGINX) rau PHP. Peb siv ib daim code los teeb qhov no.
  • WordPress xav tau HTTPS rau kev nkag
  • Tus qauv URL default yog raws li cov peev txheej
  • Teem kom raug tso cai ntawm cov ntaub ntawv kaw lus rau WordPress directory.

tsab ntawv 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

Teeb tsa NGINX Unit

Tsab ntawv teeb tsa NGINX Unit kom khiav PHP thiab txheej txheem WordPress txoj hauv kev, cais cov txheej txheem PHP namespace thiab optimizing qhov kev ua tau zoo. Nws muaj peb yam uas yuav tau saib rau ntawm no:

  • Kev them nyiaj yug rau namespaces yog txiav txim los ntawm cov xwm txheej, raws li kev kuaj xyuas tias tsab ntawv khiav hauv ib lub thawv. Qhov no yog qhov tsim nyog vim tias feem ntau cov thawv ntim khoom tsis txhawb nqa nested launching ntim.
  • Yog tias muaj kev txhawb nqa rau namespaces, lov tes taw lub namespace network. Qhov no yog tso cai rau WordPress txuas rau ob qho kawg thiab muaj nyob rau hauv lub vev xaib tib lub sijhawm.
  • Cov txheej txheem ntau tshaj plaws yog txhais raws li hauv qab no: (Muaj lub cim xeeb rau kev khiav MariaDB thiab NGINX Uniy) / (RAM txwv hauv PHP + 5)
    Tus nqi no yog teem rau hauv NGINX Unit nqis.

Tus nqi no kuj txhais tau tias ib txwm muaj tsawg kawg yog ob qhov txheej txheem PHP khiav, uas yog qhov tseem ceeb vim tias WordPress ua ntau qhov kev thov asynchronous rau nws tus kheej, thiab tsis muaj cov txheej txheem ntxiv, khiav xws li WP-Cron yuav tawg. Tej zaum koj yuav xav nce lossis txo cov kev txwv no raws li koj qhov chaw nyob hauv zos, vim tias cov chaw tsim ntawm no yog kev saib xyuas. Ntawm cov tshuab tsim khoom feem ntau, qhov chaw nyob nruab nrab ntawm 10 thiab 100.

tsab ntawv 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

Teeb tsa NGINX

Configuring Basic NGINX Settings

Tsab ntawv tsim ib daim ntawv teev npe rau NGINX cache thiab tom qab ntawd tsim cov ntaub ntawv teeb tsa tseem ceeb nginx.conf. Them mloog mus rau tus naj npawb ntawm cov txheej txheem handler thiab qhov chaw ntawm qhov siab tshaj plaws cov ntaub ntawv loj rau upload. Kuj tseem muaj cov kab uas suav nrog cov ntaub ntawv compression nqis tau teev tseg hauv ntu tom ntej, ua raws li cov chaw caching.

tsab ntawv 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

Teeb tsa NGINX compression

Compressing cov ntsiab lus ntawm ya ua ntej xa mus rau cov neeg siv khoom yog ib txoj hauv kev zoo los txhim kho qhov chaw ua haujlwm, tab sis tsuas yog compression raug teeb tsa kom raug. Tshooj lus ntawm tsab ntawv no yog ua raws li kev teeb tsa ntawm no.

tsab ntawv 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

Teeb tsa NGINX rau WordPress

Tom ntej no, tsab ntawv tsim cov ntaub ntawv teeb tsa rau WordPress default.conf hauv phau ntawv teev khoom conf.d. Nws yog configured ntawm no:

  • Ua kom TLS daim ntawv pov thawj tau txais los ntawm Let's Encrypt ntawm Certbot (kev teeb tsa yuav nyob rau hauv ntu tom ntej)
  • Configuring TLS kev ruaj ntseg teeb tsa raws li cov lus pom zoo los ntawm Let's Encrypt
  • Qhib caching hla kev thov rau 1 teev los ntawm lub neej ntawd
  • Disable nkag nkag nkag, nrog rau kev txiav txim yuam kev yog tias tsis pom cov ntaub ntawv, rau ob qho kev thov cov ntaub ntawv: favicon.ico thiab robots.txt
  • Tiv thaiv kev nkag mus rau cov ntaub ntawv zais thiab qee cov ntaub ntawv .phptxhawm rau tiv thaiv kev nkag mus tsis raug cai lossis tsis xav pib
  • Disable nkag nkag nkag rau cov ntaub ntawv zoo li qub thiab font
  • Header kev teeb tsa Access-Control-Allow-Origin rau cov ntaub ntawv font
  • Ntxiv routing rau index.php thiab lwm yam statics.

tsab ntawv 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

Teeb tsa Certbot rau daim ntawv pov thawj los ntawm Let's Encrypt thiab rov pib dua lawv

Certbot yog ib qho cuab yeej pub dawb los ntawm Electronic Frontier Foundation (EFF) uas tso cai rau koj kom tau txais thiab rov ua dua daim ntawv pov thawj TLS los ntawm Let's Encrypt. Tsab ntawv ua cov hauv qab no los teeb tsa Certbot los ua cov ntawv pov thawj los ntawm Let's Encrypt hauv NGINX:

  • Nres NGINX
  • Downloads pom zoo TLS nqis
  • Khiav Certbot kom tau txais daim ntawv pov thawj rau lub xaib
  • Rov pib NGINX kom siv daim ntawv pov thawj
  • Configures Certbot khiav txhua hnub ntawm 3:24 AM txhawm rau xyuas seb daim ntawv pov thawj yuav tsum tau rov ua dua tshiab, thiab yog tias tsim nyog, rub tawm daim ntawv pov thawj tshiab thiab rov pib NGINX.

tsab ntawv 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

Ntxiv customization ntawm koj qhov chaw

Peb tau tham saum toj no hais txog yuav ua li cas peb tsab ntawv teeb tsa NGINX thiab NGINX Unit los ua haujlwm rau qhov chaw tsim khoom npaj nrog TLSSSL enabled. Koj tseem tuaj yeem, nyob ntawm koj qhov kev xav tau, ntxiv rau yav tom ntej:

  • kev txhawb nqa Brotli, txhim kho on-the-fly compression dua HTTPS
  • Mod Kev Ruaj Ntseg с cov cai rau wordpresslos tiv thaiv kev tawm tsam tsis siv neeg ntawm koj qhov chaw
  • Thaub rau WordPress uas haum koj
  • Kev tiv thaiv nrog kev pab AppArmor (hauv Ubuntu)
  • Postfix lossis msmtp yog li WordPress tuaj yeem xa ntawv
  • Tshawb xyuas koj lub xaib kom koj nkag siab ntau npaum li cas nws tuaj yeem daws tau

Rau qhov chaw ua haujlwm zoo dua, peb pom zoo kom hloov kho mus rau NGINX Plus, peb cov khoom lag luam, qib kev lag luam raws li qhib qhov chaw NGINX. Nws cov neeg yuav khoom yuav tau txais ib qho dynamically loaded Brotli module, nrog rau (rau tus nqi ntxiv) NGINX ModSecurity WAF. Peb kuj muab NGINX App Tiv Thaiv, WAF module rau NGINX Plus raws li kev lag luam-kev ruaj ntseg tshuab los ntawm F5.

NB Rau kev txhawb nqa ntawm qhov chaw thauj khoom hnyav, koj tuaj yeem tiv tauj cov kws tshaj lij sab qab teb choj. Peb yuav ua kom ceev thiab txhim khu kev qha ua haujlwm ntawm koj lub vev xaib lossis kev pabcuam raws li kev thauj khoom.

Tau qhov twg los: www.hab.com