Ho kenya WordPress ka boiketsetso ka Unit ea NGINX le Ubuntu

Ho kenya WordPress ka boiketsetso ka Unit ea NGINX le Ubuntu

Ho na le lithupelo tse ngata mabapi le mokhoa oa ho kenya WordPress, patlo ea Google ea "WordPress install" e tla hlahisa liphetho tse ka bang halofo ea milione. Leha ho le joalo, ha e le hantle, ho na le litataiso tse fokolang haholo har'a tsona, ho latela hore na u ka kenya le ho lokisa WordPress le tsamaiso ea motheo ea ts'ebetso e le hore ba khone ho tšehetsa nako e telele. Mohlomong litlhophiso tse nepahetseng li itšetlehile haholo ka litlhoko tse itseng, kapa sena se bakoa ke taba ea hore tlhaloso e qaqileng e etsa hore sehlooho se be thata ho bala.

Sengoliloeng sena, re tla leka ho kopanya tse ntle ka ho fetesisa tsa lefats'e ka ho fana ka sengoloa sa bash ho kenya WordPress ka bo eona ho Ubuntu, le ho tsamaea ho eona, ho hlalosa hore na sekhechana ka seng se etsa eng, hammoho le ho sekisetsa hoo re ho entseng ho e nts'etsapele. . Haeba u mosebelisi ea tsoetseng pele, u ka tlola mongolo oa sengoloa le feela nka script bakeng sa liphetoho le tšebeliso tikolohong ea hau. Sephetho sa script ke mokhoa o tloaelehileng oa ho kenya WordPress ka tšehetso ea Lets Encrypt, e sebetsang ho NGINX Unit mme e loketse tšebeliso ea tlhahiso.

Moralo o ntlafalitsoeng oa ho tsamaisa WordPress o sebelisa Setsi sa NGINX o hlalositsoe ho sengoloa sa khale, joale re tla boela re hlophise lintho tse neng li sa koaheloa moo (joalo ka lithutong tse ling tse ngata):

  • WordPress CLI
  • Ha re Encrypt le Litifikeiti tsa TLSSSL
  • Nchafatso ea boiketsetso ea litifikeiti
  • NGINX caching
  • Khatello ea NGINX
  • Tšehetso ea HTTPS le HTTP/2
  • Tshebetso ea Boiketsetso

Sengoloa se tla hlalosa ho kenngoa ho seva se le seng, se tla amohela ka nako e ts'oanang seva sa ts'ebetso e tsitsitseng, seva sa ts'ebetso ea PHP, le database. Kenyelletso e ts'ehetsang baamoheli le lits'ebeletso tse ngata ke taba e ka bang teng nakong e tlang. Haeba u batla hore re ngole ka ntho e seng lihloohong tsena, ngola litlhalosong.

litlhokahalo

  • Seva ea nkho (LXC kapa LXD), mochine oa sebele, kapa seva sa tšepe se tloaelehileng se nang le bonyane 512MB ea RAM le Ubuntu 18.04 kapa e ncha e kentsoeng.
  • Likou tse fumanehang marang-rang 80 le 443
  • Lebitso la sebaka le amanang le aterese ea IP ea sechaba ea seva sena
  • Ho fihlella motso (sudo).

Kakaretso ea Meaho

Mehaho e tšoana le e hlalositsoeng pejana, sesebelisoa sa marang-rang sa mekhahlelo e meraro. E na le mangolo a PHP a sebetsang ho enjene ea PHP le lifaele tse tsitsitseng tse sebetsoang ke seva sa marang-rang.

Ho kenya WordPress ka boiketsetso ka Unit ea NGINX le Ubuntu

Melao-motheo e mengata

  • Litaelo tse ngata tsa tlhophiso ho script li phuthetsoe haeba maemo a ho hloka matla: script e ka tsamaisoa ka makhetlo a mangata ntle le kotsi ea ho fetola litlhophiso tse seng li ntse li le teng.
  • Sengoloa se leka ho kenya software ho tsoa ho polokelo, kahoo o ka sebelisa lintlafatso tsa sistimi ka taelo e le 'ngoe (apt upgrade bakeng sa Ubuntu).
  • Litaelo li leka ho bona hore li sebetsa ka har'a sets'oants'o e le hore li ka fetola litlhophiso tsa tsona ka nepo.
  • Bakeng sa ho beha palo ea lits'ebetso tsa likhoele ho qala ho li-setting, sengoloa se leka ho hakanya litlhophiso tsa othomathike tsa ho sebetsa ka har'a lijana, metjhini e fumanehang, le li-server tsa Hardware.
  • Ha re hlalosa litlhophiso, re lula re nahana pele ho tsohle ka automation, eo, re ts'epang, e tla ba motheo oa ho iketsetsa lisebelisoa tsa hau joalo ka khoutu.
  • Litaelo tsohle li tsamaisoa joalo ka mosebelisi motso, hobane ba fetola litlhophiso tsa motheo tsa tsamaiso, empa ka ho toba WordPress e sebetsa e le motho ea tloaelehileng.

Ho beha mefuta-futa ea tikoloho

Beha maemo a latelang a tikoloho pele o sebelisa script:

  • WORDPRESS_DB_PASSWORD - password ea database ea WordPress
  • WORDPRESS_ADMIN_USER - Lebitso la admin la WordPress
  • WORDPRESS_ADMIN_PASSWORD - password ea admin ea WordPress
  • WORDPRESS_ADMIN_EMAIL - Imeile ea admin ea WordPress
  • WORDPRESS_URL ke URL e felletseng ea sebaka sa WordPress, ho qala ka https://.
  • LETS_ENCRYPT_STAGING - e se nang letho, empa ka ho beha boleng ho 1, o tla sebelisa li-server tsa Let's Encrypt staging, tse hlokahalang bakeng sa ho kopa setifikeiti khafetsa ha u leka litlhophiso tsa hau, ho seng joalo Let's Encrypt e ka thibela aterese ea hau ea IP ka nakoana ka lebaka la palo e kholo ea likopo. .

Sengoloa se hlahloba hore na mefuta ena e amanang le WordPress e behiloe le ho tsoa haeba ho se joalo.
Script lines 572-576 hlahloba boleng LETS_ENCRYPT_STAGING.

Ho beha mefuta e fapaneng ea tikoloho

Sengoloa meleng ea 55-61 se beha mefuta e latelang ea tikoloho, ebang ke boleng bo thata kapa ho sebelisa boleng bo fumanoeng ho tsoa ho mefuta e behiloeng karolong e fetileng:

  • DEBIAN_FRONTEND="noninteractive" - E bolella lits'ebetso hore li sebetsa ka har'a script le hore ha ho na monyetla oa ho sebelisana le basebelisi.
  • WORDPRESS_CLI_VERSION="2.4.0" ke mofuta oa ts'ebeliso ea WordPress CLI.
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" - Checksum ea faele ea ts'ebetso ea WordPress CLI 2.4.0 (mofuta o hlalositsoe ho feto-fetoha WORDPRESS_CLI_VERSION). Sengoloa se moleng oa 162 se sebelisa boleng bona ho lekola hore na faele e nepahetseng ea WordPress CLI e jarollotsoe.
  • UPLOAD_MAX_FILESIZE="16M" - boholo ba boholo ba faele bo ka romelloang ho WordPress. Setting ena e sebelisoa libakeng tse 'maloa, kahoo ho bonolo ho e beha sebakeng se le seng.
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)" - lebitso la moamoheli oa sistimi, le nkiloe ho mofuta oa WORDPRESS_URL. E sebelisetsoa ho fumana litifikeiti tse nepahetseng tsa TLS/SSL ho Let's Encrypt hammoho le netefatso ea kahare ea WordPress.
  • NGINX_CONF_DIR="/etc/nginx" - tsela e eang bukeng e nang le litlhophiso tsa NGINX, ho kenyelletsa le faele ea mantlha nginx.conf.
  • CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}" - tsela e lebang Setifikeiti sa Let's Encrypt bakeng sa sebaka sa WordPress, se fumanoeng ho tsoa ho mefuta e fapaneng TLS_HOSTNAME.

Ho abela lebitso la moamoheli ho seva sa WordPress

Mongolo o beha lebitso la moamoheli oa seva hore le ts'oane le lebitso la sebaka sa sebaka seo. Sena ha se hlokehe, empa ho bonolo haholoanyane ho romela mangolo a tsoang ka SMTP ha u seta seva se le seng, joalo ka ha se hlophisitsoe ke mongolo.

script khoutu

# 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

Ho eketsa lebitso la moamoheli ho /etc/hosts

Tlatsetso WP-Cron e sebelisetsoang ho etsa mesebetsi ea nakoana, e hloka hore WordPress e khone ho iphumanela eona ka HTTP. Ho etsa bonnete ba hore WP-Cron e sebetsa ka nepo libakeng tsohle, sengoloa se eketsa mohala faeleng / joalo / mabothoe le hore WordPress e ka iphumanela eona ka sebopeho sa loopback:

script khoutu

# 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

Ho kenya lisebelisoa tse hlokahalang bakeng sa mehato e latelang

Lingoliloeng tse ling kaofela li hloka mananeo a itseng 'me li nka hore lipolokelo li ntse li le teng. Re ntlafatsa lenane la polokelo, ka mor'a moo re kenya lisebelisoa tse hlokahalang:

script khoutu

# 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

Ho eketsa NGINX Unit le NGINX Repositories

Sengoloa se kenya NGINX Unit le mohloli o bulehileng oa NGINX ho tsoa litsing tsa semmuso tsa NGINX ho etsa bonnete ba hore liphetolelo tse nang le lipache tsa morao-rao tsa ts'ireletso le litokiso tsa liphoso li sebelisoa.

Sengoloa se eketsa polokelo ea Unit ea NGINX ebe sebaka sa polokelo ea NGINX, se eketsa linotlolo tsa polokelo le lifaele tsa tlhophiso. apt, e hlalosang mokhoa oa ho fumana libaka tsa polokelo ka Inthanete.

Ho kenngoa ha sebele ha NGINX Unit le NGINX ho etsahala karolong e latelang. Re kenya li-repositories esale pele hore re se ke ra tlameha ho nchafatsa metadata makhetlo a mangata, e leng se etsang hore ho kengoa ka potlako.

script khoutu

# 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

Ho kenya NGINX, NGINX Unit, PHP MariaDB, Certbot (Ha re Encrypt) le litšepiso tsa bona

Hang ha lipolokelo tsohle li kentsoe, nchafatsa metadata 'me u kenye lits'ebetso. Liphutheloana tse kentsoeng ke script li boetse li kenyelletsa likeketso tsa PHP tse khothalelitsoeng ha u sebelisa WordPress.org

script khoutu

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

Ho theha PHP hore e sebelisoe le NGINX Unit le WordPress

Script e theha faele ea li-setting bukeng conf.d. Sena se beha boholo ba boholo ba faele bakeng sa ho kenya PHP, se bulela tlhahiso ea phoso ea PHP ho STDERR kahoo li tla ngolloa ho NGINX Unit log, ebe e tsosolosa Unit ea NGINX.

script khoutu

# 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

E totobatsa Litlhophiso tsa Database tsa MariaDB bakeng sa WordPress

Re khethile MariaDB ho feta MySQL kaha e na le mesebetsi e mengata ea sechaba hape e ka etsahala e fana ka tshebetso e betere ka kamehla (mohlomong, ntho e 'ngoe le e' ngoe e bonolo ho feta mona: ho kenya MySQL, o hloka ho eketsa polokelo e 'ngoe, hoo e ka bang. mofetoleli).

Sengoloa se theha database se secha mme se theha lintlha tsa ho fihlella WordPress ka sebopeho sa loopback:

script khoutu

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

Ho kenya Lenaneo la WordPress CLI

Mothating ona, script e kenya lenaneo WP-CLI. Ka eona, o ka kenya le ho laola litlhophiso tsa WordPress ntle le ho hlophisa lifaele ka letsoho, ho ntlafatsa database, kapa ho kenya phanele ea taolo. E ka boela ea sebelisoa ho kenya lihlooho le li-add-on le ho ntlafatsa WordPress.

script khoutu

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

Ho kenya le ho lokisa WordPress

Script e kenya mofuta oa morao-rao oa WordPress bukeng ea libuka /var/www/wordpresshape o fetola li-setting:

  • Khokahano ea database e sebetsa holim'a socket ea unix ho e-na le TCP ho loopback ho fokotsa sephethephethe sa TCP.
  • WordPress e eketsa selelekela https:// ho URL haeba bareki ba hokahana le NGINX holim'a HTTPS, hape ba romella lebitso la moeti le hole (joalokaha le fanoe ke NGINX) ho PHP. Re sebelisa sekhechana sa khoutu ho theha sena.
  • WordPress e hloka HTTPS bakeng sa ho kena
  • Sebopeho sa kamehla sa URL se ipapisitse le lisebelisoa
  • E beha litumello tse nepahetseng ho sistimi ea faele bakeng sa directory ea WordPress.

script khoutu

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

Ho theha Yuniti ea NGINX

Sengoloa se hlophisa Yuniti ea NGINX ho tsamaisa PHP le ho sebetsana le litsela tsa WordPress, ho arola sebaka sa mabitso sa ts'ebetso ea PHP le ho ntlafatsa maemo a ts'ebetso. Ho na le likarolo tse tharo tseo u lokelang ho li ela hloko mona:

  • Tšehetso ea libaka tsa mabitso e khethoa ke maemo, ho itšetlehile ka ho hlahloba hore na mongolo o sebetsa ka har'a sets'oants'o. Sena sea hlokahala hobane li-setups tse ngata ha li tšehetse ho qalisoa ha lijana.
  • Haeba ho na le ts'ehetso ea libaka tsa mabitso, tima sebaka sa mabitso netweke. Sena ke ho lumella WordPress ho hokela ho li-endpoints ka bobeli le ho ba teng ho webosaete ka nako e le 'ngoe.
  • Palo e kholo ea lits'ebetso e hlalosoa ka tsela e latelang: (Mohopolo o teng oa ho tsamaisa MariaDB le NGINX Uniy)/(Moeli oa RAM ho PHP + 5)
    Boleng bona bo behiloe litlhophisong tsa Yuniti ea NGINX.

Boleng bona bo boetse bo fana ka maikutlo a hore ho na le bonyane mekhoa e 'meli ea PHP e sebetsang, e leng ea bohlokoa hobane WordPress e iketsetsa likōpo tse ngata tse sa tšoaneng,' me ntle le mekhoa e meng, e sebetsang e.g. WP-Cron e tla robeha. U ka 'na ua batla ho eketsa kapa ho fokotsa meeli ena ho latela litlhophiso tsa sebaka sa heno, hobane litlhophiso tse entsoeng mona lia boloka. Litsamaisong tse ngata tsa tlhahiso, litlhophiso li pakeng tsa 10 le 100.

script khoutu

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

Ho theha NGINX

Ho hlophisa Litlhophiso tsa mantlha tsa NGINX

Script e etsa directory bakeng sa cache ea NGINX ebe e theha faele e kholo ea tlhophiso nginx.conf. Ela hloko palo ea lits'ebetso tsa mohlokomeli le maemo a boholo ba faele bakeng sa ho kenya. Hape ho na le mola o kenyelletsang faele ea litlhophiso tsa compression e hlalositsoeng karolong e latelang, e lateloa ke litlhophiso tsa caching.

script khoutu

# 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

Ho theha compression ea NGINX

Ho hatella litaba ka fofa pele u li romella ho bareki ke mokhoa o motle oa ho ntlafatsa ts'ebetso ea sebaka sa marang-rang, empa ha feela khatello e lokiselitsoe ka nepo. Karolo ena ea script e ipapisitse le litlhophiso ho tloha mona.

script khoutu

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

Ho theha NGINX bakeng sa WordPress

Ka mor'a moo, script e etsa faele ea tlhophiso bakeng sa WordPress default.conf lenaneng conf.d. E hlophisitsoe mona:

  • Ho kenya litifikeiti tsa TLS tse amohetsoeng ho tsoa ho Let's Encrypt ka Certbot (ho e hlophisa ho tla ba karolong e latelang)
  • Ho lokisa litlhophiso tsa ts'ireletso tsa TLS ho ipapisitse le likhothaletso tse tsoang ho Let's Encrypt
  • E nolofalletsa ho boloka likopo tse tlotsoeng bakeng sa hora e le 'ngoe feela
  • Tlosa mokhoa oa ho rekota, hammoho le ho rekota ka phoso haeba faele e sa fumanehe, bakeng sa lifaele tse peli tse kopiloeng tse tloaelehileng: favicon.ico le robots.txt
  • Thibela ho fihlella lifaele tse patiloeng le lifaele tse ling .phpho thibela phihlello e seng molaong kapa qalo e sa reroang
  • Tlosa mokhoa oa ho kena bakeng sa lifaele tse tsitsitseng le tsa fonte
  • Tlhophiso ea lihlooho Access-Laola-Lumella-Qalo bakeng sa lifaele tsa fonte
  • Ho eketsa routing bakeng sa index.php le tse ling tse statics.

script khoutu

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

Ho theha Certbot bakeng sa litifikeiti tse tsoang ho Let's Encrypt le ho li nchafatsa ka bo eona

Bopaki ke sesebelisoa sa mahala se tsoang ho Electronic Frontier Foundation (EFF) se u lumellang hore u fumane le ho nchafatsa litifikeiti tsa TLS ho tsoa ho Let's Encrypt. Sengoloa se etsa se latelang ho hlophisa Certbot ho sebetsa setifikeiti ho tsoa ho Let's Encrypt in NGINX:

  • E emisa NGINX
  • Litlhophiso tsa TLS tse khothalelitsoeng ho jarolla
  • E tsamaisa Certbot ho fumana litifikeiti tsa sebaka sa marang-rang
  • E qala NGINX hape ho sebelisa litifikeiti
  • E lokisa Certbot hore e sebetse letsatsi le leng le le leng ka 3:24 AM ho lekola hore na litifikeiti li hloka ho nchafatsoa, ​​'me ha ho hlokahala, khoasolla litifikeiti tse ncha ebe u qala NGINX bocha.

script khoutu

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

Tlhahiso e eketsehileng ea sebaka sa hau sa marang-rang

Re buile ka holimo mabapi le hore na script ea rona e hlophisa joang NGINX le NGINX Unit ho sebeletsa sebaka se lokiselitsoeng tlhahiso le TLSSSL e nolofalitsoeng. Hape, ho latela litlhoko tsa hau, u ka eketsa nakong e tlang:

  • tshehetso Brotli, e ntlafalitse khatello ea ho fofa holim'a HTTPS
  • Tšireletso ea Mod с melao bakeng sa wordpressho thibela litlhaselo tse iketsang sebakeng sa hau sa marang-rang
  • Khutlela bakeng sa WordPress e u tšoanelang
  • Tšireletso ka thuso AppArmor (ho Ubuntu)
  • Postfix kapa msmtp kahoo WordPress e ka romella mangolo
  • Ho hlahloba sebaka sa hau sa marang-rang e le hore u utloisise hore na se ka sebetsana le sephethephethe se kae

Bakeng sa ts'ebetso e ntle ea sebaka sa marang-rang, re khothaletsa ho ntlafatsa ho NGINX Plus, sehlahisoa sa rona sa khoebo, sa boemo ba khoebo se thehiloeng mohloling o bulehileng oa NGINX. Bangoli ba eona ba tla fumana module ea Brotli e tlatsitsoeng ka matla, hammoho le (bakeng sa tefo e eketsehileng) NGINX ModSecurity WAF. Re boetse re fana ka NGINX App Sireletsa, WAF module bakeng sa NGINX Plus e thehiloeng ho theknoloji ea ts'ireletso ea indasteri e tsoang ho F5.

NB Bakeng sa ts'ehetso ea sebaka sa marang-rang se tletseng haholo, o ka ikopanya le litsebi Southbridge. Re tla netefatsa ts'ebetso e potlakileng le e tšepahalang ea sebaka sa hau sa marang-rang kapa tšebeletso tlas'a mojaro ofe kapa ofe.

Source: www.habr.com