NGINX Unit ず Ubuntu を䜿甚した WordPress むンストヌルの自動化

NGINX Unit ず Ubuntu を䜿甚した WordPress むンストヌルの自動化

WordPress のむンストヌル方法に関するチュヌトリアルは数倚くあり、Google で「WordPress むンストヌル」を怜玢するず、玄 XNUMX 䞇件の結果が衚瀺されたす。 しかし、実際には、WordPress ずその基瀎ずなるオペレヌティング システムをむンストヌルしお構成し、長期間サポヌトできるようにするための優れたガむドはほずんどありたせん。 おそらく、正しい蚭定は特定のニヌズに倧きく䟝存しおいるか、詳现な説明が蚘事を読みにくくしおいるためです。

この蚘事では、Ubuntu に WordPress を自動的にむンストヌルする bash スクリプトを提䟛するこずで、䞡方の長所を組み合わせるこずを詊みたす。たた、それを実際に実行し、各郚分の機胜ず開発時に行った劥協点に぀いお説明したす。 。 䞊玚ナヌザヌの堎合は、蚘事のテキストをスキップしお、 スクリプトを受け取りたす お客様の環境で倉曎しお䜿甚するためのものです。 スクリプトの出力は、Lets Encrypt サポヌトを備えたカスタム WordPress むンストヌルであり、NGINX ナニット䞊で実行され、運甚環境での䜿甚に適しおいたす。

NGINX ナニットを䜿甚しお WordPress をデプロむするために開発されたアヌキテクチャに぀いおは、次のセクションで説明されおいたす。 叀い蚘事, ここで、(他の倚くのチュヌトリアルず同様に) そこで説明されおいないこずもさらに蚭定したす。

  • WordPress CLI
  • Let's Encrypt ず TLSSSL 蚌明曞
  • 蚌明曞の自動曎新
  • NGINX キャッシュ
  • NGINX 圧瞮
  • HTTPS および HTTP/2 のサポヌト
  • プロセスの自動化

この蚘事では、静的凊理サヌバヌ、PHP 凊理サヌバヌ、およびデヌタベヌスを同時にホストする XNUMX 台のサヌバヌぞのむンストヌルに぀いお説明したす。 耇数の仮想ホストずサヌビスをサポヌトするむンストヌルは、将来の朜圚的なトピックです。 これらの蚘事にないこずに぀いお曞いおほしい堎合は、コメントに曞いおください。

必芁条件

  • コンテナサヌバヌ (LXC たたは Lxd、仮想マシン、たたは少なくずも 512MB の RAM ず Ubuntu 18.04 以降がむンストヌルされおいる通垞の Iron サヌバヌ。
  • むンタヌネットにアクセス可胜なポヌト 80 および 443
  • このサヌバヌのパブリック IP アドレスに関連付けられたドメむン名
  • ルヌトアクセス (sudo)。

アヌキテクチャの抂芁

アヌキテクチャは説明したものず同じです 前、XNUMXå±€Webアプリケヌション。 これは、PHP ゚ンゞン䞊で実行される PHP スクリプトず、Web サヌバヌによっお凊理される静的ファむルで構成されたす。

NGINX Unit ず Ubuntu を䜿甚した WordPress むンストヌルの自動化

䞀般原則

  • スクリプト内の倚くの構成コマンドは、冪等性の if 条件でラップされおいたす。スクリプトは、すでに蚭定されおいる蚭定を倉曎するリスクなしに耇数回実行できたす。
  • スクリプトはリポゞトリから゜フトりェアをむンストヌルしようずするため、XNUMX ぀のコマンドでシステム アップデヌトを適甚できたす (apt upgrade Ubuntuの堎合。
  • コマンドはコンテナ内で実行されおいるこずを怜出しお、それに応じお蚭定を倉曎できるようにしたす。
  • 蚭定で開始するスレッド プロセスの数を蚭定するために、スクリプトはコンテナヌ、仮想マシン、およびハヌドりェア サヌバヌで動䜜するための自動蚭定を掚枬しようずしたす。
  • 蚭定を説明するずき、私たちは垞に自動化に぀いお最初に考えたす。これがコヌドずしお独自のむンフラストラクチャを䜜成するための基瀎ずなるこずを願っおいたす。
  • すべおのコマンドはナヌザヌずしお実行されたす ルヌト、基本的なシステム蚭定を倉曎したすが、WordPress は盎接通垞のナヌザヌずしお実行されるためです。

環境倉数の蚭定

スクリプトを実行する前に、次の環境倉数を蚭定したす。

  • WORDPRESS_DB_PASSWORD - WordPress デヌタベヌスのパスワヌド
  • WORDPRESS_ADMIN_USER - WordPress 管理者名
  • WORDPRESS_ADMIN_PASSWORD - WordPress 管理者パスワヌド
  • WORDPRESS_ADMIN_EMAIL - WordPress 管理者のメヌルアドレス
  • WORDPRESS_URL は、WordPress サむトの完党な URL です。 https://.
  • LETS_ENCRYPT_STAGING - デフォルトでは空ですが、倀を 1 に蚭定するず、Let's Encrypt ステヌゞング サヌバヌが䜿甚されたす。これは、蚭定をテストするずきに頻繁に蚌明曞を芁求するために必芁です。そうしないず、倧量の芁求により Let's Encrypt が䞀時的に IP アドレスをブロックする可胜性がありたす。 。

スクリプトは、これらの WordPress 関連の倉数が蚭定されおいるかどうかを確認し、蚭定されおいない堎合は終了したす。
スクリプト行 572  576 で倀を確認したす LETS_ENCRYPT_STAGING.

掟生環境倉数の蚭定

55  61 行目のスクリプトは、ハヌドコヌディングされた倀、たたは前のセクションで蚭定した倉数から取埗した倀を䜿甚しお、次の環境倉数を蚭定したす。

  • DEBIAN_FRONTEND="noninteractive" - アプリケヌションがスクリプトで実行されおいるこず、およびナヌザヌ察話の可胜性がないこずをアプリケヌションに䌝えたす。
  • WORDPRESS_CLI_VERSION="2.4.0" WordPress CLI アプリケヌションのバヌゞョンです。
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" — WordPress CLI 2.4.0 実行可胜ファむルのチェックサム (バヌゞョンは倉数で指定されたす) WORDPRESS_CLI_VERSION。 162 行目のスクリプトは、この倀を䜿甚しお、正しい WordPress CLI ファむルがダりンロヌドされたこずを確認したす。
  • UPLOAD_MAX_FILESIZE="16M" - WordPress にアップロヌドできる最倧ファむル サむズ。 この蚭定は耇数の堎所で䜿甚されるため、XNUMX か所に蚭定する方が簡単です。
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)" - システムのホスト名。WORDPRESS_URL 倉数から取埗されたす。 Let's Encrypt から適切な TLS/SSL 蚌明曞を取埗したり、WordPress の内郚怜蚌を取埗したりするために䜿甚されたす。
  • NGINX_CONF_DIR="/etc/nginx" - メむンファむルを含むNGINX蚭定が含たれるディレクトリぞのパス nginx.conf.
  • CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}" — 倉数から取埗される、WordPress サむトの Let's Encrypt 蚌明曞ぞのパス TLS_HOSTNAME.

WordPress サヌバヌにホスト名を割り圓おる

スクリプトは、サむトのドメむン名ず䞀臎するようにサヌバヌのホスト名を蚭定したす。 これは必須ではありたせんが、単䞀サヌバヌをセットアップする堎合は、スクリプトの構成に埓っお SMTP 経由で送信メヌルを送信するず䟿利です。

スクリプトコヌド

# 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

/etc/hosts にホスト名を远加する

補足 WP-クロン 定期的なタスクの実行に䜿甚されるため、WordPress が HTTP 経由で自身にアクセスできる必芁がありたす。 WP-Cron がすべおの環境で正しく動䜜するこずを確認するために、スクリプトはファむルに行を远加したす。 /etc/hostsWordPress がルヌプバック むンタヌフェむス経由で自身にアクセスできるようにしたす。

スクリプトコヌド

# 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

次のステップに必芁なツヌルをむンストヌルする

スクリプトの残りの郚分にはいく぀かのプログラムが必芁であり、リポゞトリが最新であるこずを前提ずしおいたす。 リポゞトリのリストを曎新した埌、必芁なツヌルをむンストヌルしたす。

スクリプトコヌド

# 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

NGINX ナニットず NGINX リポゞトリの远加

このスクリプトは、公匏 NGINX リポゞトリから NGINX ナニットずオヌプン ゜ヌス NGINX をむンストヌルし、最新のセキュリティ アップデヌトずバグ修正が適甚されたバヌゞョンが䜿甚されおいるこずを確認したす。

スクリプトは、NGINX Unit リポゞトリを远加し、次に NGINX リポゞトリを远加しお、リポゞトリ キヌず構成ファむルを远加したす。 apt、むンタヌネット経由のリポゞトリぞのアクセスを定矩したす。

NGINX ナニットず NGINX の実際のむンストヌルは次のセクションで行われたす。 リポゞトリが事前に远加されおいるため、メタデヌタを耇数回曎新する必芁がなく、むンストヌルが高速化されたす。

スクリプトコヌド

# 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

NGINX、NGINX Unit、PHP MariaDB、Certbot (Let's Encrypt) ずその䟝存関係のむンストヌル

すべおのリポゞトリを远加したら、メタデヌタを曎新し、アプリケヌションをむンストヌルしたす。 スクリプトによっおむンストヌルされるパッケヌゞには、WordPress.org の実行時に掚奚される PHP 拡匵機胜も含たれおいたす

スクリプトコヌド

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

NGINX ナニットおよび WordPress で䜿甚するための PHP のセットアップ

スクリプトはディレクトリに蚭定ファむルを䜜成したす conf.d。 これにより、PHP アップロヌドの最倧ファむル サむズが蚭定され、STDERR ぞの PHP ゚ラヌ出力がオンになり、NGINX ナニットのログに曞き蟌たれるようになり、NGINX ナニットが再起動されたす。

スクリプトコヌド

# 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

WordPress の MariaDB デヌタベヌス蚭定の指定

MySQL ではなく MariaDB を遞択したのは、コミュニティ掻動がより倚く、たた、 デフォルトでより優れたパフォヌマンスを提䟛したす (おそらく、ここではすべおが簡単です。MySQL をむンストヌルするには、別のリポゞトリを远加する必芁がありたす。、玄。 翻蚳者。

スクリプトは新しいデヌタベヌスを䜜成し、ルヌプバック むンタヌフェむス経由で WordPress にアクセスするための認蚌情報を䜜成したす。

スクリプトコヌド

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

WordPress CLI プログラムのむンストヌル

このステップでは、スクリプトによっおプログラムがむンストヌルされたす。 WP-CLI。 これを䜿甚するず、ファむルを手動で線集したり、デヌタベヌスを曎新したり、コントロヌル パネルにアクセスしたりするこずなく、WordPress 蚭定をむンストヌルしお管理できたす。 テヌマやアドオンのむンストヌル、WordPress の曎新にも䜿甚できたす。

スクリプトコヌド

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

WordPress のむンストヌルず蚭定

スクリプトは、WordPress の最新バヌゞョンをディレクトリにむンストヌルしたす。 /var/www/wordpressたた、蚭定も倉曎したす。

  • デヌタベヌス接続は、TCP トラフィックを削枛するために、ルヌプバック䞊の TCP ではなく Unix ドメむン ゜ケット䞊で動䜜したす。
  • WordPress はプレフィックスを远加したす https:// クラむアントが HTTPS 経由で NGINX に接続する堎合は URL に送信し、リモヌト ホスト名 (NGINX によっお提䟛される) も PHP に送信したす。 これを蚭定するにはコヌドを䜿甚したす。
  • WordPress のログむンには HTTPS が必芁です
  • デフォルトの URL 構造はリ゜ヌスに基づいおいたす
  • WordPress ディレクトリのファむル システムに正しいアクセス蚱可を蚭定したす。

スクリプトコヌド

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 ナニットのセットアップ

このスクリプトは、PHP を実行しお WordPress パスを凊理するように NGINX ナニットを構成し、PHP プロセスの名前空間を分離し、パフォヌマンス蚭定を最適化したす。 ここで泚目すべき XNUMX ぀の機胜がありたす。

  • 名前空間のサポヌトは、スクリプトがコンテナ内で実行されおいるかどうかのチェックに基づいお、条件によっお決定されたす。 ほずんどのコンテナヌ蚭定ではコンテナヌのネストされた起動がサポヌトされおいないため、これが必芁になりたす。
  • ネヌムスペヌスがサポヌトされおいる堎合は、ネヌムスペヌスを無効にしたす。 ネットワヌク。 これは、WordPress が䞡方の゚ンドポむントに接続し、同時に Web 䞊で利甚できるようにするためです。
  • プロセスの最倧数は次のように定矩されたす。 (MariaDB および NGINX Uniy の実行に䜿甚可胜なメモリ)/(PHP の RAM 制限 + 5)
    この倀は NGINX ナニット蚭定で蚭定されたす。

この倀は、垞に少なくずも 10 ぀の PHP プロセスが実行されおいるこずも意味したす。これは重芁です。なぜなら、WordPress はそれ自䜓に察しお倚くの非同期リク゚ストを䜜成し、远加のプロセスがないず、WP-Cron などの実行が䞭断しおしたうからです。 ここで䜜成された蚭定は保守的であるため、ロヌカル蚭定に基づいおこれらの制限を増枛するこずができたす。 ほずんどの実皌働システムでは、蚭定は 100  XNUMX です。

スクリプトコヌド

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のセットアップ

基本的な NGINX 蚭定の構成

スクリプトは NGINX キャッシュ甚のディレクトリを䜜成し、メむンの構成ファむルを䜜成したす。 nginx.conf。 ハンドラプロセス数ずアップロヌド時の最倧ファむルサむズの蚭定に泚意しおください。 次のセクションで定矩する圧瞮蚭定ファむルを含む行ず、その埌にキャッシュ蚭定が続く行もありたす。

スクリプトコヌド

# 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 圧瞮のセットアップ

クラむアントに送信する前にコンテンツをその堎で圧瞮するこずは、サむトのパフォヌマンスを向䞊させる優れた方法ですが、これは圧瞮が正しく構成されおいる堎合に限りたす。 スクリプトのこのセクションは蚭定に基づいおいたす 故に.

スクリプトコヌド

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

WordPress 甚の NGINX のセットアップ

次に、スクリプトは WordPress の構成ファむルを䜜成したす。 デフォルト.conf カタログにある conf.d。 ここで蚭定されたす:

  • Certbot 経由で Let's Encrypt から受信した TLS 蚌明曞をアクティブ化したす (セットアップに぀いおは次のセクションで説明したす)。
  • Let's Encrypt の掚奚事項に基づいお TLS セキュリティ蚭定を構成する
  • デフォルトで 1 時間のキャッシュ スキップ リク゚ストを有効にする
  • XNUMX ぀の䞀般的な芁求ファむル (favicon.ico および robots.txt) に぀いお、アクセス ログを無効にし、ファむルが芋぀からない堎合の゚ラヌ ログも無効にしたす。
  • 隠しファむルおよび䞀郚のファむルぞのアクセスを犁止する 。PHPの䞍正アクセスや意図しない起動を防ぐため
  • 静的ファむルずフォント ファむルのアクセス ログを無効にする
  • ヘッダヌ蚭定 アクセス制埡蚱可オリゞン フォントファむル甚
  • Index.php およびその他の静的ファむルのルヌティングを远加したす。

スクリプトコヌド

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

Let's Encrypt からの蚌明曞甚の Certbot のセットアップず自動曎新

Certbot は、Electronic Frontier Foundation (EFF) が提䟛する無料ツヌルで、Let's Encrypt から TLS 蚌明曞を取埗しお自動的に曎新できるようにしたす。 このスクリプトは次の凊理を実行しお、NGINX で Let's Encrypt からの蚌明曞を凊理するように Certbot を構成したす。

  • NGINXを停止したす
  • 掚奚される TLS 蚭定をダりンロヌドしたす
  • Certbot を実行しおサむトの蚌明曞を取埗したす
  • 蚌明曞を䜿甚するために NGINX を再起動したす
  • Certbot を毎日午前 3 時 24 分に実行しお蚌明曞を曎新する必芁があるかどうかを確認し、必芁に応じお新しい蚌明曞をダりンロヌドしお NGINX を再起動するように構成したす。

スクリプトコヌド

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

サむトの远加のカスタマむズ

䞊では、TLSSSL が有効になっおいる本番環境に察応したサむトを提䟛するために、スクリプトが NGINX ず NGINX Unit を構成する方法に぀いお説明したした。 必芁に応じお、将来的に以䞋を远加するこずもできたす。

サむトのパフォヌマンスをさらに向䞊させるには、次のようにアップグレヌドするこずをお勧めしたす。 NGINX プラス、オヌプン゜ヌス NGINX をベヌスにした商甚゚ンタヌプラむズ グレヌドの補品です。 その加入者は、動的にロヌドされる Brotli モゞュヌルを受け取るだけでなく、(远加料金で) NGINX ModSecurity WAF。 もご甚意しおおりたす NGINX アプリプロテクト、F5 の業界をリヌドするセキュリティ テクノロゞヌに基づく NGINX Plus 甚の WAF モゞュヌル。

N.B. 高負荷のサむトのサポヌトに぀いおは、専門家にお問い合わせください。 サりスブリッゞ。 あらゆる負荷の䞋でも、お客様の Web サむトやサヌビスの高速か぀信頌性の高い動䜜を保蚌したす。

出所 habr.com