Automatisearje WordPress-ynstallaasje mei NGINX Unit en Ubuntu

Automatisearje WordPress-ynstallaasje mei NGINX Unit en Ubuntu

D'r is d'r in protte materiaal oer it ynstallearjen fan WordPress; in Google-sykje nei "WordPress install" sil sawat in heal miljoen resultaten weromjaan. D'r binne lykwols eins heul pear nuttige hantliedingen dy't jo kinne helpe WordPress en it ûnderlizzende bestjoeringssysteem te ynstallearjen en te konfigurearjen sadat se oer in lange perioade kinne wurde stipe. Miskien binne de juste ynstellingen sterk ôfhinklik fan jo spesifike behoeften, of it kin wêze om't de detaillearre útlis it artikel lestich makket om te lêzen.

Yn dit artikel sille wy besykje it bêste fan beide wrâlden byinoar te bringen troch in bash-skript te leverjen om WordPress automatysk op Ubuntu te ynstallearjen, en wy sille der trochrinne, útlizze wat elk stik docht en de ôfwikselingen dy't wy makke hawwe by it ûntwerpen it. As jo ​​in betûfte brûker binne, kinne jo de tekst fan it artikel oerslaan en gewoan nim it skript foar wiziging en gebrûk yn jo omjouwings. De útfier fan it skript is in oanpaste WordPress-ynstallaasje mei Lets Encrypt-stipe, rint op NGINX Unit en geskikt foar yndustrieel gebrûk.

De ûntwikkele arsjitektuer foar it ynsetten fan WordPress mei NGINX Unit wurdt beskreaun yn âlder artikel, sille wy no ek dingen fierder konfigurearje dy't dêr net behannele binne (lykas yn in protte oare tutorials):

  • WordPress CLI
  • Lit ús fersiferje en TLSSSL-sertifikaten
  • Automatyske sertifikaatfernijing
  • NGINX Caching
  • NGINX kompresje
  • HTTPS en HTTP/2-stipe
  • Proses automatisearring

It artikel sil ynstallaasje beskriuwe op ien server, dy't tagelyk in statyske ferwurkingstsjinner, in PHP-ferwurkingstsjinner en in databank sil hostje. Ynstallaasje mei stipe foar meardere firtuele hosts en tsjinsten is in potinsjeel ûnderwerp foar de takomst. As jo ​​​​wolle dat wy skriuwe oer iets dat net yn dizze artikels stiet, skriuw dan yn 'e kommentaren.

easken

  • Tsjinner container (LXC of LXD), in firtuele masine, as in gewoane hardware-tsjinner, mei op syn minst 512MB RAM en Ubuntu 18.04 of mear resint ynstalleare.
  • Ynternet tagonklike havens 80 en 443
  • De domeinnamme dy't ferbûn is mei it iepenbiere IP-adres fan dizze tsjinner
  • Tagong mei rootrjochten (sudo).

Arsjitektuer oersjoch

De arsjitektuer is itselde as beskreaun earder, in trije-tier webapplikaasje. It bestiet út PHP-skripts útfierd op 'e PHP-motor en statyske bestannen ferwurke troch de webserver.

Automatisearje WordPress-ynstallaasje mei NGINX Unit en Ubuntu

Algemiene begjinsels

  • In protte konfiguraasjekommando's yn in skript wurde ferpakt yn as betingsten foar idempotinsje: it skript kin meardere kearen wurde útfierd sûnder it risiko fan wizigjen fan ynstellings dy't al klear binne.
  • It skript besiket software te ynstallearjen fan repositories, sadat jo systeemupdates kinne tapasse yn ien kommando (apt upgrade foar Ubuntu).
  • Teams besykje te ûntdekken dat se yn in kontener rinne, sadat se har ynstellings dêrmei feroarje kinne.
  • Om it oantal threadprosessen yn te stellen dy't wurde lansearre yn 'e ynstellings, besiket it skript de automatyske ynstellingen te rieden foar wurkjen yn konteners, firtuele masines en hardwareservers.
  • By it beskriuwen fan ynstellings tinke wy altyd earst oan automatisearring, dy't wy hoopje dat de basis sil wurde foar it meitsjen fan jo eigen ynfrastruktuer as koade.
  • Alle kommando's wurde útfierd fan 'e brûker woartel, om't se de basissysteemynstellingen feroarje, mar WordPress sels rint as in gewoane brûker.

Ynstelle omjouwingsfariabelen

Stel de folgjende omjouwingsfariabelen yn foardat jo it skript útfiere:

  • WORDPRESS_DB_PASSWORD - Wachtwurd foar WordPress-database
  • WORDPRESS_ADMIN_USER - WordPress admin brûkersnamme
  • WORDPRESS_ADMIN_PASSWORD - WordPress admin wachtwurd
  • WORDPRESS_ADMIN_EMAIL - WordPress admin e-post
  • WORDPRESS_URL - folsleine URL fan 'e WordPress-side, begjinnend mei https://.
  • LETS_ENCRYPT_STAGING - standert leech, mar troch de wearde op 1 yn te stellen, sille jo de stagingservers fan Let's Encrypt brûke, dy't nedich binne om faak sertifikaten oan te freegjen by it testen fan jo ynstellings, oars kin Let's Encrypt jo IP-adres tydlik blokkearje fanwege it grutte oantal oanfragen.

It skript kontrolearret dat dizze WordPress-relatearre fariabelen ynsteld binne en útgean as se net binne.
Skript rigels 572-576 kontrolearje de wearde LETS_ENCRYPT_STAGING.

It ynstellen fan ôflaat omjouwingsfariabelen

It skript op rigels 55-61 stelt de folgjende omjouwingsfariabelen yn, itsij op wat hurd-kodearre wearde of mei in wearde ôflaat fan de fariabelen ynsteld yn 'e foarige seksje:

  • DEBIAN_FRONTEND="noninteractive" - fertelt applikaasjes dat se rinne yn in skript en d'r is gjin mooglikheid fan brûkersynteraksje.
  • WORDPRESS_CLI_VERSION="2.4.0" - WordPress CLI-ferzje fan 'e applikaasje.
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" - kontrôlesum fan it útfierbere bestân WordPress CLI 2.4.0 (de ferzje wurdt oanjûn yn 'e fariabele WORDPRESS_CLI_VERSION). It skript op rigel 162 brûkt dizze wearde om te kontrolearjen dat it juste WordPress CLI-bestân is ynladen.
  • UPLOAD_MAX_FILESIZE="16M" - de maksimale triemgrutte dy't kin wurde upload nei WordPress. Dizze ynstelling wurdt op ferskate plakken brûkt, dus it is makliker om it op ien plak yn te stellen.
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)" - systeem hostnamme, ekstrahearre út de WORDPRESS_URL fariabele. Wurdt brûkt om passende TLS/SSL-sertifikaten te krijen fan Let's Encrypt, lykas ek foar ynterne WordPress-ferifikaasje.
  • NGINX_CONF_DIR="/etc/nginx" - paad nei de map mei NGINX-ynstellingen, ynklusyf it haadbestân nginx.conf.
  • CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}" - paad nei Let's Encrypt-sertifikaten foar de WordPress-side, krigen fan 'e fariabele TLS_HOSTNAME.

Hostnamme tawize oan WordPress-tsjinner

It skript stelt de hostnamme fan de tsjinner yn, sadat de wearde oerienkomt mei de domeinnamme fan de side. Dit is net nedich, mar it is handiger om útgeande e-post fia SMTP te ferstjoeren by it ynstellen fan in inkele tsjinner, lykas ynsteld troch it skript.

skript koade

# 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

Hostnamme tafoegje oan /etc/hosts

Oanfolling WP-Cron brûkt om periodike taken út te fieren, fereasket WordPress om tagong te krijen fia HTTP. Om der wis fan te wêzen dat WP-Cron yn alle omjouwings goed wurket, foeget it skript in rigel ta oan it bestân / etc / hostssadat WordPress himsels tagong kin fia de loopback-ynterface:

skript koade

# 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

Ynstallearje de ark nedich foar folgjende stappen

De rest fan it skript fereasket wat programma's en giet derfan út dat de repositories bywurke binne. Wy aktualisearje de list mei repositories, en ynstallearje dan de nedige ark:

skript koade

# 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

It tafoegjen fan de NGINX Unit en NGINX repositories

It skript ynstallearret NGINX Unit en iepen boarne NGINX fan 'e offisjele NGINX-repositories om te soargjen dat de ferzjes mei de lêste befeiligingsupdates en bugfixes wurde brûkt.

It skript foeget it NGINX Unit repository ta en dan it NGINX repository, it tafoegjen fan de repositories-kaai en ynstellingsbestannen apt, it definiearjen fan tagong ta repositories fia it ynternet.

De eigentlike ynstallaasje fan 'e NGINX Unit en NGINX komt foar yn' e folgjende paragraaf. Wy foegje repositories foar om it bywurkjen fan metadata meardere kearen te foarkommen, wêrtroch ynstallaasje flugger wurdt.

skript koade

# 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

Ynstallearje fan NGINX, NGINX Unit, PHP MariaDB, Certbot (Let's Encrypt) en har ôfhinklikens

Sadree't alle repositories binne tafoege, aktualisearje wy de metadata en ynstallearje de applikaasjes. De pakketten ynstalleare troch it skript omfetsje ek PHP-tafoegings oanrikkemandearre by it útfieren fan WordPress.org

skript koade

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

PHP ynstelle foar gebrûk mei NGINX Unit en WordPress

It skript makket in ynstellingsbestân yn 'e map konf.d. Dit stelt de maksimale triem-uploadgrutte foar PHP yn, makket it mooglik om PHP-flaters út te fieren nei STDERR sadat se wurde oanmeld by de NGINX-ienheid, en de NGINX-ienheid opnij starte.

skript koade

# 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

MariaDB-databaseynstellingen ynstelle foar WordPress

Wy hawwe MariaDB keazen oer MySQL om't it mear mienskipsaktiviteit hat en ek kin leveret standert bettere prestaasjes (Wierskynlik is alles hjir ienfâldiger: om MySQL te ynstallearjen, moatte jo in oare repository tafoegje, ca. oersetter).

It skript makket in nije databank en makket WordPress tagongsgegevens fia de loopback-ynterface:

skript koade

# 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;"

It ynstallearjen fan it WordPress CLI-programma

Op dizze stap ynstalleart it skript it programma WP-CLI. Mei it kinne jo WordPress-ynstellingen ynstallearje en beheare sûnder bestannen manuell te bewurkjen, de databank bywurkje of oanmelde by it kontrôlepaniel. It kin ek brûkt wurde om tema's en tafoegings te ynstallearjen en WordPress te aktualisearjen.

skript koade

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

Ynstallearje en konfigurearje WordPress

It skript ynstalleart de lêste ferzje fan WordPress yn 'e map /var/www/wordpress, en feroaret ek de ynstellings:

  • De databankferbining wurket oer in unix-domein-socket ynstee fan TCP op loopback om TCP-ferkear te ferminderjen.
  • WordPress foeget in foarheaksel ta https:// nei de URL as kliïnten ferbine mei NGINX oer HTTPS, en stjoert ek de hostnamme op ôfstân (lykas fersoarge troch NGINX) nei PHP. Wy brûke in stikje koade om dit op te setten.
  • WordPress hat HTTPS nedich om oan te melden
  • URL-struktuer is stille boarne basearre
  • Korrekte triemsysteem tagongsrjochten binne ynsteld foar de WordPress map.

skript koade

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

NGINX Unit ynstelle

It skript konfigurearret NGINX Unit om PHP út te fieren en WordPress-paden te behanneljen, it isolearjen fan de nammeromte fan PHP-prosessen en it optimalisearjen fan prestaasjesynstellingen. D'r binne trije funksjes dy't it wurdich omtinken te jaan:

  • Namespace-stipe wurdt bepaald troch betingst, basearre op it kontrolearjen dat it skript yn 'e kontener rint. Dit is nedich om't de measte kontenerynstellingen gjin geneste rinnen fan konteners stypje.
  • As der stipe is foar nammeromten, is de nammeromte útskeakele netwurk. Dit is nedich om WordPress tagelyk te ferbinen mei einpunten en tagonklik te wêzen op it ynternet.
  • It maksimum oantal prosessen wurdt bepaald as folget: (Beskikber ûnthâld foar it útfieren fan MariaDB en NGINX Uniy) / (RAM-limyt yn PHP + 5)
    Dizze wearde is ynsteld yn 'e NGINX Unit ynstellings.

Dizze wearde hâldt ek yn dat d'r altyd op syn minst twa PHP-prosessen rinne, wat wichtich is, om't WordPress in protte asynchrone oanfragen foar himsels makket, en sûnder ekstra prosessen dy't rinne, sil bygelyks WP-Cron brekke. Jo kinne dizze grinzen fergrutsje of ferminderje op basis fan jo lokale ynstellings, om't de ynstellings dy't hjir makke binne konservatyf binne. Op de measte produksjesystemen binne de ynstellingen tusken 10 en 100.

skript koade

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 ynstelle

Basis NGINX-ynstellingen konfigurearje

It skript makket in map foar de NGINX-cache en makket dan it haadkonfiguraasjetriem oan nginx.conf. Jou omtinken oan it oantal handlerprosessen en de maksimale triemgrutte-ynstelling foar download. D'r is ek in line wêrop it kompresje-ynstellingsbestân, definieare yn 'e folgjende seksje, is ferbûn, folge troch caching-ynstellingen.

skript koade

# 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-kompresje ynstelle

It komprimearjen fan ynhâld op 'e flecht foardat jo it nei kliïnten ferstjoere is in geweldige manier om sideprestaasjes te ferbetterjen, mar allinich as kompresje goed is ynsteld. Dizze seksje fan it skript is basearre op de ynstellings fan hjir.

skript koade

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 ynstelle foar WordPress

Dêrnei makket it skript in konfiguraasjetriem foar WordPress default.conf yn 'e katalogus konf.d. Hjir is it konfigurearre:

  • TLS-sertifikaten aktivearje ûntfongen fan Let's Encrypt fia Certbot (it konfigurearje sil yn 'e folgjende seksje)
  • Konfigurearje TLS-feiligensynstellingen basearre op oanbefellings fan Let's Encrypt
  • Standert ynskeakelje caching fan oerslein fersyk foar 1 oere
  • Skeakelje tagongslogging út, lykas flaterlogging as it bestân net fûn wurdt, foar twa gewoane oanfrege bestannen: favicon.ico en robots.txt
  • Wegerje tagong ta ferburgen bestannen en guon bestannen .phpom yllegale tagong of ûnbedoelde lansearring te foarkommen
  • Skeakelje tagongslogging út foar statyske en lettertypebestannen
  • It ynstellen fan de titel Access-Control-Tastean-Origin foar lettertypebestannen
  • Rûting tafoegje foar index.php en oare statyk.

skript koade

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

Certbot konfigurearje foar Let's Encrypt-sertifikaten en automatysk fernije

certbot is in fergese ark fan 'e Electronic Frontier Foundation (EFF) wêrmei jo TLS-sertifikaten kinne krije en automatysk fernije fan Let's Encrypt. It skript fiert de folgjende stappen út om Certbot te konfigurearjen om sertifikaten te ferwurkjen fan Let's Encrypt yn NGINX:

  • Stops NGINX
  • Downloads oanrikkemandearre TLS ynstellings
  • Rint Certbot om sertifikaten te krijen foar de side
  • Start NGINX opnij om sertifikaten te brûken
  • Konfigurearret Certbot om alle dagen om 3:24 oere te rinnen om te kontrolearjen op sertifikaatfernijings en, as nedich, nije sertifikaten downloade en NGINX opnij starte.

skript koade

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

Oanfoljende oanpassing fan jo side

Wy hawwe hjirboppe praat oer hoe't ús skript NGINX en NGINX Unit konfigurearret om in produksje-klear webside te tsjinjen mei TLSSSL ynskeakele. Jo kinne ek, ôfhinklik fan jo behoeften, yn 'e takomst tafoegje:

  • Stypje Brotli, ferbettere on-the-fly kompresje oer HTTPS
  • Mod Feiligens с regels foar WordPressom automatyske oanfallen op jo side te foarkommen
  • Reservekopy foar WordPress, geskikt foar dy
  • Beskerming troch AppArmor (op Ubuntu)
  • Postfix of msmtp sadat WordPress e-post ferstjoere kin
  • Kontrolearje jo side sadat jo begripe hoefolle ferkear it kin omgean

Foar noch bettere sideprestaasjes riede wy oan om te upgrade nei NGINX Plus, ús kommersjeel produkt fan bedriuwskwaliteit basearre op de iepen boarne NGINX. De abonnees sille in dynamysk laden Brotli-module krije, lykas (foar in ekstra fergoeding) NGINX ModSecurity WAF. Wy biede ek NGINX App beskermje, in WAF-module foar NGINX Plus basearre op yndustryliedende feiligenstechnology fan F5.

NB Foar stipe fan in webside mei hege lading kinne jo kontakt opnimme mei spesjalisten súdlike brêge. Wy sille soargje foar rappe en betroubere wurking fan jo webside of tsjinst ûnder elke lading.

Boarne: www.habr.com