Te whakaaunoa i te whakaurunga WordPress me te NGINX Unit me te Ubuntu

Te whakaaunoa i te whakaurunga WordPress me te NGINX Unit me te Ubuntu

He maha nga rauemi kei reira mo te whakauru i te WordPress; he rapunga a Google mo te "WordPress install" ka hoki mai mo te hawhe miriona nga hua. Heoi ano, he iti noa nga kaiarahi whaihua kei reira hei awhina i a koe ki te whakauru me te whirihora i te WordPress me te punaha whakahaere o raro kia taea ai te tautoko mo te waa roa. Ko nga tautuhinga tika ka whakawhirinaki nui ki o hiahia motuhake, na te mea pea na te whakamaramatanga taipitopito ka uaua te panui o te tuhinga.

I roto i tenei tuhinga, ka ngana matou ki te whakakotahi i nga mea pai rawa atu o nga ao e rua ma te whakarato i te tuhinga bash ki te whakauru aunoa i te WordPress ki runga i te Ubuntu, ka haere maatau, me te whakamarama he aha nga mahi a ia waahanga me nga mahi hokohoko i mahia e matou i roto i te hoahoa. te reira. Mena he kaiwhakamahi mohio koe, ka taea e koe te peke i te tuhinga o te tuhinga me te tika tangohia te tuhinga mo te whakarereke me te whakamahi i o taiao. Ko te putanga o te tuhinga he whakaurunga WordPress ritenga me te tautoko Lets Encrypt, e rere ana i runga i te NGINX Unit me te pai mo te whakamahi ahumahi.

Ko te hoahoanga whakawhanakehia mo te whakamahi i te WordPress ma te whakamahi i te NGINX Unit e whakaahuatia ana i roto tuhinga tawhito, ka whirihora ano tatou i nga mea kaore i hipokina ki reira (penei i etahi atu akoranga):

  • WordPress CLI
  • Kia Whakamuna me nga tiwhikete TLSSSL
  • Te whakahou tiwhikete aunoa
  • NGINX Keteroki
  • NGINX kōpeketanga
  • Tautoko HTTPS me HTTP/2
  • Tukatuka aunoa

Ka whakaahuahia e te tuhinga te whakaurunga ki runga i te tūmau kotahi, ka manaaki i te wā kotahi te tūmau tukatuka pateko, te tūmau tukatuka PHP, me te pātengi raraunga. Ko te whakauru me te tautoko mo nga kaihautu mariko maha me nga ratonga he kaupapa pea mo nga ra kei mua. Mena kei te hiahia koe ki te tuhi maatau mo tetahi mea kaore i roto i enei tuhinga, tuhia ki nga korero.

whakaritenga

  • ipu tūmau (LXC ranei LXD), he mihini mariko, he tūmau pūmārō auau ranei, me te 512MB o te RAM me te Ubuntu 18.04, he mea tata ake ranei.
  • Ko nga tauranga 80 me te 443 e waatea ana ki te Ipurangi
  • Ko te ingoa rohe e hono ana ki te wāhitau IP tūmatanui o tēnei tūmau
  • Te uru me nga tika pakiaka (sudo).

Tirohanga hoahoanga

He rite tonu te hoahoanga ki te whakaahuatanga Tuhinga o mua, he tono tukutuku e toru nga taumata. Kei roto ko nga tuhinga PHP i mahia i runga i te miihini PHP me nga konae pateko i tukatukahia e te tūmau tukutuku.

Te whakaaunoa i te whakaurunga WordPress me te NGINX Unit me te Ubuntu

Kaupapa Matua

  • He maha nga whakahau whirihoranga i roto i te tuhinga ka takai ki roto i nga tikanga mo te ngoikoretanga: ka taea te whakahaere i te tuhinga i nga wa maha me te kore e tupono ki te whakarereke i nga tautuhinga kua reri.
  • Ka ngana te tuhinga ki te whakauru i nga rorohiko mai i nga putunga, kia taea ai e koe te tono whakahōutanga punaha ki te whakahau kotahi (apt upgrade mo Ubuntu).
  • Ka ngana nga kapa ki te kite kei te rere ratou i roto i tetahi ipu kia taea ai e ratou te whakarereke i o raatau tautuhinga.
  • Hei tautuhi i te maha o nga tukanga miro ka whakarewahia i roto i nga tautuhinga, ka ngana te tuhinga ki te tohu i nga tautuhinga aunoa mo te mahi i roto i nga ipu, miihini mariko, me nga taputapu taputapu.
  • I te wa e whakaahua ana i nga tautuhinga, ka whakaaro tuatahi matou mo te automation, e tumanako ana matou ka noho hei turanga mo te hanga i o ake hanganga hei waehere.
  • Ka whakahaerehia nga whakahau katoa mai i te kaiwhakamahi pakiaka, no te mea ka huri ratou i nga tautuhinga punaha taketake, engari ko te WordPress ano e rere ana hei kaiwhakamahi auau.

Te tautuhi i nga taurangi taiao

Tautuhia nga taurangi taiao e whai ake nei i mua i te whakahaere i te tuhinga:

  • WORDPRESS_DB_PASSWORD — Kupuhipa pātengi raraunga WordPress
  • WORDPRESS_ADMIN_USER - Kaiwhakamahi ingoa kaiwhakamahi WordPress
  • WORDPRESS_ADMIN_PASSWORD - Kupuhipa kaiwhakahaere WordPress
  • WORDPRESS_ADMIN_EMAIL — Email admin WordPress
  • WORDPRESS_URL – URL katoa o te pae WordPress, timata mai https://.
  • LETS_ENCRYPT_STAGING — karekau ma te taunoa, engari ma te tautuhi i te uara ki te 1, ka whakamahi koe i nga kaitoro mahi a Let's Encrypt, e tika ana ki te tono i nga tiwhikete i te wa e whakamatautau ana i o tautuhinga, mena ka taea e Let's Encrypt te aukati i to wahitau IP mo te wa poto na te nui o nga tono.

Ka tirohia e te tuhinga kua whakaritea enei taurangi e pa ana ki te WordPress ka puta ki te kore.
Ko nga rarangi tuhinga 572-576 tirohia te uara LETS_ENCRYPT_STAGING.

Te tautuhi i nga taurangi taiao i ahu mai

Ko te tuhinga kei runga i nga rarangi 55-61 e whakatakoto ana i nga taurangi taiao e whai ake nei, ki etahi uara-whakawaehere pakeke, ki te whakamahi ranei i tetahi uara i ahu mai i nga taurangi kua whakaritea i te waahanga o mua:

  • DEBIAN_FRONTEND="noninteractive" — ka kii ki nga tono kei te whakahaerehia i roto i te tuhinga, kaore he waahi o te taunekeneke a te kaiwhakamahi.
  • WORDPRESS_CLI_VERSION="2.4.0" — Putanga WordPress CLI o te tono.
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" — takitaki o te konae whakahaere WordPress CLI 2.4.0 (kua tohua te putanga ki te taurangi WORDPRESS_CLI_VERSION). Ko te tuhinga kei te rarangi 162 e whakamahi ana i tenei uara hei manatoko i te tika te konae WordPress CLI i tangohia.
  • UPLOAD_MAX_FILESIZE="16M" — te rahi o nga konae ka taea te tuku ki te WordPress. He maha nga waahi ka whakamahia tenei tautuhinga, no reira he maamaa ake te whakanoho ki te waahi kotahi.
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)" — ingoa kaihautū pūnaha, i tangohia mai i te taurangi WORPRESS_URL. I whakamahia ki te tiki tiwhikete TLS/SSL e tika ana mai i Let's Encrypt, me te manatoko WordPress o roto.
  • NGINX_CONF_DIR="/etc/nginx" — ara ki te whaiaronga me nga tautuhinga NGINX, tae atu ki te konae matua nginx.conf.
  • CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}" — ara ki te Whakamuna Tiwhikete mo te pae WordPress, i riro mai i te taurangi TLS_HOSTNAME.

Tautapa i te ingoa kaihautū ki te tūmau WordPress

Ka tautuhia e te tuhinga te ingoa kaihautu o te tūmau kia rite te uara ki te ingoa rohe o te pae. Ehara tenei i te mea e tika ana, engari he pai ake te tuku mēra putaatu ma te SMTP i te wa e whakatuu ana i te tūmau kotahi, i whirihorahia e te tuhinga.

waehere hōtuhi

# 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

Te taapiri i te ingoa kaihautu ki /etc/hosts

Tāpiri WP‑Cron whakamahia ki te whakahaere i nga mahi o ia wa, me uru a WordPress ki a ia ano ma te HTTP. Kia mohio kei te mahi tika a WP-Cron i nga taiao katoa, ka taapirihia e te tuhinga he raina ki te konae / Etc / manokia taea ai e WordPress te uru atu ki a ia ano ma te atanga takahuri:

waehere hōtuhi

# 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

Te whakauru i nga taputapu e hiahiatia ana mo nga taahiraa e whai ake nei

Ko te toenga o te tuhinga e hiahia ana ki etahi papatono me te whakaaro kei te noho hou nga putunga. Ka whakahouhia e matou te rarangi o nga putunga, ka whakauruhia nga taputapu e tika ana:

waehere hōtuhi

# 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

Te taapiri i te Waehe NGINX me nga putunga NGINX

Ka whakauruhia e te tuhinga te Waehe NGINX me te puna tuwhera NGINX mai i nga whare pupuri NGINX whaimana hei whakarite kia whakamahia nga putanga me nga whakahoutanga haumarutanga hou me nga whakatikatika bug.

Ka taapirihia e te tuhinga te kohinga NGINX Unit katahi ko te kohinga NGINX, me te taapiri i nga kii putunga me nga konae tautuhinga. apt, te tautuhi i te uru ki nga whare pupuri ma te Ipurangi.

Ko te whakaurunga tuuturu o te NGINX Unit me te NGINX ka puta i te waahanga e whai ake nei. I mua i te taapiri i nga putunga hei karo i te whakahou i nga metadata i nga wa maha, kia tere ake te whakaurunga.

waehere hōtuhi

# 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

Te whakauru i te NGINX, NGINX Unit, PHP MariaDB, Certbot (Me Whakamuna) me o raatau whakawhirinaki

Kia taapirihia nga putunga katoa, ka whakahouhia e matou nga metadata me te whakauru i nga tono. Kei roto hoki i nga kohinga kua whakauruhia e te tuhinga nga taapiri PHP e taunaki ana i te wa e whakahaere ana i te WordPress.org

waehere hōtuhi

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

Te whakarite PHP mo te whakamahi me te NGINX Unit me te WordPress

Ka waihangahia e te tuhinga he konae tautuhinga ki te whaiaronga conf.d. Ka whakatauhia te rahi o te tukunga ake o nga konae mo PHP, ka taea te whakaputa hapa PHP ki STDERR kia takiuru ki te Waehe NGINX, ka whakaara ano i te Waehe NGINX.

waehere hōtuhi

# 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

Te tautuhi i nga Tautuhinga Raraunga Raraunga MariaDB mo te WordPress

I whiriwhiria e matou a MariaDB mo MySQL na te mea he nui ake nga mahi a te hapori, ka taea hoki he pai ake te mahi ma te taunoa (Akene, he maamaa ake nga mea katoa i konei: ki te whakauru i a MySQL, me taapiri koe i tetahi atu putunga, āhua. kaiwhakamaori).

Ka hangaia e te tuhinga he papaa raraunga hou me te hanga i nga tohu urunga WordPress ma te atanga loopback:

waehere hōtuhi

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

Te whakauru i te kaupapa WordPress CLI

I tenei taahiraa ka whakauruhia e te tuhinga te papatono WP CLI. Ma te reira, ka taea e koe te whakauru me te whakahaere i nga tautuhinga WordPress me te kore e whakatika a-ringa i nga konae, whakahou i te paataka, takiuru ranei ki te paewhiri mana. Ka taea hoki te whakamahi ki te whakauru i nga kaupapa me nga taapiri me te whakahou i te WordPress.

waehere hōtuhi

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

Tāuta me te Whirihora WordPress

Ka whakauruhia e te tuhinga te putanga hou o WordPress ki roto i te whaiaronga /var/www/wordpress, ka huri ano hoki i nga tautuhinga:

  • Ka mahi te hononga pātengi raraunga i runga i te turanga rohe unix hei utu mo te TCP i runga i te whakamuri hei whakaiti i te hokohoko TCP.
  • Ka taapirihia e WordPress he prefix https:// ki te URL mena ka hono nga kaihoko ki te NGINX ma runga i te HTTPS, ka tukuna ano hoki te ingoa kaihautu mamao (na te NGINX i homai) ki PHP. Ka whakamahia e matou tetahi waahanga waehere hei whakarite i tenei.
  • Kei te hiahia a WordPress ki te HTTPS ki te takiuru
  • Ko te hanganga URL kei te noho puku i te rauemi
  • Kua whakaritea nga whakaaetanga punaha konae mo te raarangi WordPress.

waehere hōtuhi

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

Te whakatu NGINX Unit

Ka whirihorahia e te tuhinga te Waehe NGINX hei whakahaere i te PHP me te hapai i nga huarahi WordPress, te wehe i te mokowāingoa o nga tukanga PHP me te arotau i nga tautuhinga mahi. E toru nga waahanga e tika ana kia aro ki:

  • Ko te tautoko mokowāingoa ka whakatauhia e te ahuatanga, i runga i te tirotiro kei te rere te tuhinga ki roto i te ipu. He mea tika tenei na te mea kaore te nuinga o nga tatūnga ipu e tautoko ana i te whakahaere ohanga o nga ipu.
  • Mena he tautoko mo nga mokowā ingoa, kua monoa te mokowāingoa whatunga. He mea tika tenei kia taea ai e WordPress te hono atu ki nga waahi mutunga ka uru ki te Ipurangi.
  • Ko te maha o nga tukanga ka whakatauhia e whai ake nei: (Maharatanga e waatea ana mo te whakahaere i a MariaDB me NGINX Uniy)/(te rohe RAM kei PHP + 5)
    Kua tautuhia tenei uara ki nga tautuhinga NGINX Unit.

Ko tenei uara hoki e kii ana kei te rua nga mahi PHP e whakahaere ana, he mea nui na te mea he maha nga tono tukutahi a WordPress ki a ia ano, me te kore e rere etahi atu tukanga, hei tauira, ka pakaru a WP-Cron. Ka hiahia pea koe ki te whakanui ake, ki te whakaheke ranei i enei tepe i runga i o tautuhinga rohe, na te mea ko nga tautuhinga i hangaia i konei he mea tiaki. I te nuinga o nga punaha whakaputa ko nga tautuhinga kei waenga i te 10 me te 100.

waehere hōtuhi

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

Te whakatu NGINX

Whirihorahia nga Tautuhinga NGINX Basic

Ka hangaia e te tuhinga he whaiaronga mo te keteroki NGINX katahi ka hangaia te konae whirihoranga matua nginx.conf. Kia tupato ki te maha o nga tukanga kaihautu me te rahinga o te rahi o te konae hei tango. He raina ano kei te hono te konae tautuhinga compression, kua tautuhia i te waahanga e whai ake nei, ka whai i nga tautuhinga keteroki.

waehere hōtuhi

# 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

Te whakarite i te whakakopeketanga NGINX

Ko te whakakopeke i nga ihirangi i runga i te rere i mua i te tuku ki nga kaihoko he huarahi pai ki te whakapai ake i te mahinga o te pae, engari mena ka tika te whirihora o te kopeke. Ko tenei waahanga o te tuhinga i runga i nga tautuhinga mai i konei.

waehere hōtuhi

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

Te whakatu NGINX mo WordPress

I muri mai, ka hangaia e te tuhinga he konae whirihoranga mo WordPress default.conf i roto i te rārangi conf.d. I konei kua whirihorahia:

  • Whakahohe i nga tiwhikete TLS i riro mai i Let's Encrypt via Certbot (te whirihora ka noho ki te waahanga e whai ake nei)
  • Whirihorahia nga tautuhinga haumarutanga TLS i runga i nga taunakitanga mai i Let's Encrypt
  • Whakahohea te keteroki tono kua pekehia mo te 1 haora ma te taunoa
  • Monokia te takiuru uru, me te takiuru hapa mena kaore i kitea te konae, mo nga konae e rua e tono noa ana: favicon.ico me robots.txt
  • Whakakahoretia te uru ki nga konae huna me etahi konae .Māki te aukati i te urunga kore ture, te whakarewatanga pohehe ranei
  • Monokia te takiuru uru mo nga konae pateko me te momotuhi
  • Te whakatakoto i te taitara Uru-Mana-Tukua-Tuinga mō ngā kōnae momotuhi
  • Te taapiri i te ararere mo index.php me etahi atu taatai.

waehere hōtuhi

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

Te whirihora i te Certbot mo nga tiwhikete Let's Encrypt me te whakahou aunoa

Certbot he taputapu kore utu mai i te Electronic Frontier Foundation (EFF) ka taea e koe te tiki me te whakahou aunoa i nga tiwhikete TLS mai i Let's Encrypt. Ka mahia e te tuhinga nga mahi e whai ake nei hei whirihora i a Certbot ki te tukatuka i nga tiwhikete mai i Let's Encrypt in NGINX:

  • Ka mutu te NGINX
  • Tikina ake nga tautuhinga TLS e taunaki ana
  • Whakahaerehia ai a Certbot kia whiwhi tiwhikete mo te pae
  • Ka timata ano te NGINX ki te whakamahi i nga tiwhikete
  • Ka whirihorahia a Certbot kia rere ia ra i te 3:24 i te ata ki te tirotiro mo nga whakahoutanga tiwhikete, a, ki te tika, tango i nga tiwhikete hou ka whakaara ano i te NGINX.

waehere hōtuhi

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

Whakaritenga taapiri o to pae

I korero matou i runga ake mo te whirihora a to maatau tuhinga i te NGINX me te NGINX Unit ki te mahi i tetahi paetukutuku kua rite ki te hanga me te TLSSSL kua whakahohea. Ka taea ano e koe, i runga i o hiahia, taapiri i nga wa kei te heke mai:

  • Tautoko Brotli, te whakapai ake i runga i te rere ki runga HTTPS
  • Haumarutanga Mod с ture mo WordPresshei aukati i nga whakaeke aunoa i to pae
  • Pūrua mo WordPress, e tika ana mo koe
  • Whakahaumaru me te awhina Āpiha (i runga Ubuntu)
  • Postfix ranei msmtp kia taea e WordPress te tuku mēra
  • Te tirotiro i to pae kia mohio ai koe ki te nui o te hokohoko ka taea e ia te whakahaere

Mo te pai ake o te mahinga o te pae, ka tūtohu matou kia whakahou ake ki NGINX Plus, to tatou hua arumoni-akomanga i runga i te puna tuwhera NGINX. Ka whiwhi nga kaiohauru ki tetahi waahanga Brotli kua utaina, me (mo te utu taapiri) NGINX ModSecurity WAF. Ka tukuna ano e matou NGINX App Tiaki, he waahanga WAF mo NGINX Plus i runga i te hangarau haumaru-a-ahumahi mai i te F5.

NB Mo te tautoko i tetahi paetukutuku nui, ka taea e koe te whakapiri atu ki nga tohunga Southbridge. Ka whakarite maatau i te tere me te pono o to paetukutuku, ratonga ranei i raro i nga kawenga.

Source: will.com