Otomatik enstalasyon WordPress ak Inite NGINX ak Ubuntu

Otomatik enstalasyon WordPress ak Inite NGINX ak Ubuntu

Gen anpil materyèl sou enstale WordPress; yon rechèch Google pou "WordPress enstale" pral retounen apeprè demi milyon rezilta. Sepandan, gen aktyèlman trè kèk gid itil deyò ki ka ede w enstale ak konfigirasyon WordPress ak sistèm opere ki kache pou yo ka sipòte sou yon peryòd tan ki long. Petèt paramèt kòrèk yo depann anpil de bezwen espesifik ou yo, oswa li ka paske eksplikasyon an detay fè atik la difisil pou li.

Nan atik sa a, nou pral eseye mete ansanm pi bon nan tou de mond yo lè nou bay yon script bash otomatikman enstale WordPress sou Ubuntu, epi nou pral mache atravè li, eksplike kisa chak moso fè ak komès-off nou te fè nan konsepsyon. li. Si ou se yon itilizatè ki gen eksperyans, ou ka sote tèks la nan atik la ak jis pran script la pou modifikasyon ak itilizasyon nan anviwònman ou yo. Pwodiksyon script la se yon enstalasyon WordPress koutim ak sipò Lets Encrypt, kouri sou NGINX Unit ak apwopriye pou itilizasyon endistriyèl.

Achitekti devlope pou deplwaye WordPress lè l sèvi avèk NGINX Unit dekri nan pi gran atik, Nou pral kounye a tou konfigirasyon plis bagay ki pa te kouvri la (tankou nan anpil lòt tutoryèl):

  • WordPress CLI
  • Ann ankripte ak sètifika TLSSSL
  • Renouvèlman otomatik sètifika
  • NGINX Caching
  • NGINX konpresyon
  • HTTPS ak HTTP/2 sipò
  • Otomatik pwosesis

Atik la pral dekri enstalasyon sou yon sèl sèvè, ki pral an menm tan òganize yon sèvè pwosesis estatik, yon sèvè pwosesis PHP, ak yon baz done. Enstalasyon ak sipò pou plizyè lame vityèl ak sèvis se yon sijè potansyèl pou lavni. Si ou vle nou ekri sou yon bagay ki pa nan atik sa yo, ekri nan kòmantè yo.

Kondisyon pou

  • veso sèvè (LXC oswa LXD), yon machin vityèl, oswa yon sèvè pyès ki nan konpitè regilye, ak omwen 512MB RAM ak Ubuntu 18.04 oswa plis ki resan enstale.
  • Entènèt pò aksesib 80 ak 443
  • Non domèn ki asosye ak adrès IP piblik sèvè sa a
  • Aksè ak dwa rasin (sudo).

Apèsi sou Achitekti

Achitekti a se menm jan sa dekri pi bonè, yon aplikasyon entènèt twa-niveau. Li konsiste de script PHP egzekite sou motè PHP a ak fichye estatik ki trete pa sèvè entènèt la.

Otomatik enstalasyon WordPress ak Inite NGINX ak Ubuntu

Jeneral prensip yo

  • Anpil kòmandman konfigirasyon nan yon script yo vlope nan si kondisyon pou idempotans: script la ka kouri plizyè fwa san risk pou yo chanje paramèt ki deja pare.
  • Script la ap eseye enstale lojisyèl ki soti nan depo, kidonk, ou ka aplike mizajou sistèm nan yon sèl lòd (apt upgrade pou Ubuntu).
  • Ekip yo eseye detekte ke yo ap kouri nan yon veso pou yo ka chanje paramèt yo kòmsadwa.
  • Yo nan lòd yo mete kantite pwosesis fil yo dwe lanse nan anviwònman yo, script la ap eseye devine anviwònman yo otomatik pou travay nan resipyan, machin vityèl, ak sèvè pyès ki nan konpitè.
  • Lè nou dekri anviwònman, nou toujou panse premye sou automatisation, ki nou espere pral vin baz pou kreye pwòp enfrastrikti ou kòm kòd.
  • Tout kòmandman yo kouri soti nan itilizatè a rasin, paske yo chanje anviwònman sistèm debaz yo, men WordPress tèt li kouri kòm yon itilizatè regilye.

Mete varyab anviwònman an

Mete varyab anviwònman sa yo anvan ou kouri script la:

  • WORDPRESS_DB_PASSWORD - WordPress modpas baz done
  • WORDPRESS_ADMIN_USER - Non itilizatè admin WordPress
  • WORDPRESS_ADMIN_PASSWORD - WordPress admin modpas
  • WORDPRESS_ADMIN_EMAIL - Imel admin WordPress
  • WORDPRESS_URL – URL konplè sou sit WordPress la, kòmanse ak https://.
  • LETS_ENCRYPT_STAGING — vid pa default, men lè w mete valè a 1, ou pral sèvi ak sèvè ansèyman Let's Encrypt yo, ki nesesè pou souvan mande sètifika lè w teste anviwònman ou yo, otreman Let's Encrypt ka tanporèman bloke adrès IP ou akòz gwo kantite demann.

Script la tcheke varyab sa yo ki gen rapò ak WordPress yo mete ak sòti si yo pa.
Liy script 572-576 tcheke valè a LETS_ENCRYPT_STAGING.

Mete varyab anviwònman ki sòti

Script sou liy 55-61 mete varyab anviwònman sa yo, swa nan kèk valè ki kode difisil oswa lè l sèvi avèk yon valè ki sòti nan varyab yo mete nan seksyon anvan an:

  • DEBIAN_FRONTEND="noninteractive" — di aplikasyon yo ke yo ap kouri nan yon script epi pa gen okenn posibilite pou itilizatè entèraksyon.
  • WORDPRESS_CLI_VERSION="2.4.0" — WordPress CLI vèsyon aplikasyon an.
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" — sòm chèk nan dosye ègzèkutabl WordPress CLI 2.4.0 (vèsyon an endike nan varyab la WORDPRESS_CLI_VERSION). Script la sou liy 162 sèvi ak valè sa a pou verifye si yo te telechaje kòrèk WordPress CLI dosye a.
  • UPLOAD_MAX_FILESIZE="16M" - gwosè a maksimòm dosye ki ka telechaje sou WordPress. Anviwònman sa a itilize plizyè kote, kidonk li pi fasil pou mete l nan yon sèl kote.
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)" — Non host sistèm, ekstrè soti nan varyab WORDPRESS_URL. Itilize pou jwenn sètifika TLS/SSL apwopriye nan men Let's Encrypt, osi byen ke pou verifikasyon entèn WordPress.
  • NGINX_CONF_DIR="/etc/nginx" - chemen anyè a ak anviwònman NGINX, ki gen ladan dosye prensipal la nginx.conf.
  • CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}" — chemen an pou ann ankripte sètifika pou sit WordPress la, yo jwenn nan varyab la TLS_HOSTNAME.

Bay non host nan sèvè WordPress

Script la mete hostname sèvè a pou valè a matche ak non domèn sit la. Sa a pa nesesè, men li pi bon pou voye lapòs sortan atravè SMTP lè w ap mete yon sèl sèvè, jan script la configured.

kòd script

# 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

Ajoute non host nan /etc/hosts

Sipleman WP-Cron itilize pou kouri travay peryodik, mande WordPress pou kapab jwenn aksè nan tèt li atravè HTTP. Pou asire w ke WP-Cron travay kòrèkteman nan tout anviwònman, script la ajoute yon liy nan dosye a. / Eksetera / gen tout pouvwa apou WordPress ka jwenn aksè nan tèt li atravè koòdone loopback la:

kòd script

# 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

Enstale zouti ki nesesè pou etap ki vin apre yo

Rès script la mande kèk pwogram epi li sipoze ke depo yo ajou. Nou mete ajou lis depo, epi enstale zouti ki nesesè yo:

kòd script

# 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

Ajoute Inite NGINX ak depo NGINX yo

Script la enstale NGINX Unit ak sous louvri NGINX soti nan depo ofisyèl NGINX yo pou asire ke vèsyon yo ak dènye mizajou sekirite ak korije ensèk yo itilize.

Script la ajoute repozitwa Inite NGINX la ak Lè sa a, repozitwa NGINX la, ajoute kle depo ak dosye paramèt yo. apt, defini aksè nan depo atravè entènèt la.

Enstalasyon aktyèl la nan Inite NGINX ak NGINX rive nan pwochen seksyon an. Nou pre-ajoute depo pou evite mete ajou plizyè fwa, sa ki fè enstalasyon pi vit.

kòd script

# 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

Enstale NGINX, NGINX Unit, PHP MariaDB, Certbot (Ann ankripte) ak depandans yo

Yon fwa ke tout depo yo te ajoute, nou mete ajou metadata yo epi enstale aplikasyon yo. Pake yo enstale pa script la gen ladan tou ekstansyon PHP rekòmande lè w ap kouri WordPress.org

kòd script

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

Mete kanpe PHP pou itilize ak NGINX Unit ak WordPress

Script la kreye yon dosye paramèt nan anyè a konf. d. Sa a fikse gwosè maksimòm pou telechaje dosye a pou PHP, pèmèt erè PHP yo dwe soti nan STDERR pou yo pral konekte nan Inite NGINX la, epi rekòmanse Inite NGINX la.

kòd script

# 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

Anviwònman MariaDB Database Settings pou WordPress

Nou te chwazi MariaDB sou MySQL paske li gen plis aktivite kominote a epi li kapab tou bay pi bon pèfòmans pa default (Pwobableman, tout bagay se pi senp isit la: enstale MySQL, ou bezwen ajoute yon lòt depo, approx. tradiktè).

Script la kreye yon nouvo baz done epi kreye kalifikasyon aksè WordPress atravè koòdone loopback la:

kòd script

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

Enstale pwogram CLI WordPress la

Nan etap sa a, script la enstale pwogram nan WP-CLI. Avèk li, ou ka enstale ak jere anviwònman WordPress san yo pa bezwen manyèlman edite dosye, mete ajou baz done a, oswa konekte nan panèl la kontwòl. Li kapab tou itilize pou enstale tèm ak ajoute ak ajou WordPress.

kòd script

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

Enstale ak konfigirasyon WordPress

Script la enstale dènye vèsyon WordPress nan anyè a /var/www/wordpress, epi tou chanje anviwònman yo:

  • Koneksyon baz done a travay sou yon priz domèn Unix olye pou yo TCP sou loopback pou diminye trafik TCP.
  • WordPress ajoute yon prefiks https:// nan URL la si kliyan konekte ak NGINX sou HTTPS, epi tou voye non host la aleka (jan NGINX bay la) nan PHP. Nou itilize yon moso kòd pou mete sa a kanpe.
  • WordPress bezwen HTTPS pou konekte
  • Estrikti URL an silans baze sou resous
  • Pèmisyon sistèm dosye kòrèk yo mete pou anyè WordPress la.

kòd script

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

Mete kanpe inite NGINX

Script la configured NGINX Unit pou kouri PHP ak okipe chemen WordPress, izole espas non nan pwosesis PHP ak optimize anviwònman pèfòmans. Gen twa karakteristik ki vo peye atansyon sou:

  • Sipò espas non yo detèmine pa kondisyon, ki baze sou tcheke si script la ap kouri nan veso a. Sa a nesesè paske pifò konfigirasyon veso yo pa sipòte kouri enbrike nan veso yo.
  • Si gen sipò pou namespaces, namespace la enfim rezo. Sa a nesesè pou pèmèt WordPress konekte ansanm ak pwen final yo epi yo dwe aksesib sou entènèt la.
  • Kantite maksimòm pwosesis yo detèmine jan sa a: (Memwa ki disponib pou kouri MariaDB ak NGINX Uniy)/(limit RAM nan PHP + 5)
    Valè sa a mete nan paramèt Inite NGINX yo.

Valè sa a tou implique ke gen toujou omwen de pwosesis PHP kouri, ki enpòtan paske WordPress fè yon anpil nan demann asynchrone nan tèt li, epi san yo pa pwosesis adisyonèl kouri, pou egzanp, WP-Cron pral kraze. Ou ka vle ogmante oswa diminye limit sa yo ki baze sou anviwònman lokal ou yo, paske anviwònman yo kreye isit la se konsèvatif. Sou pifò sistèm pwodiksyon paramèt yo se ant 10 ak 100.

kòd script

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

Mete kanpe NGINX

Konfigirasyon Paramèt NGINX debaz yo

Script la kreye yon anyè pou kachèt NGINX ak Lè sa a, kreye dosye konfigirasyon prensipal la nginx.conf. Peye atansyon sou kantite pwosesis moun k ap okipe yo ak anviwònman maksimòm gwosè dosye a pou telechaje. Genyen tou yon liy sou ki fichye paramèt konpresyon an, ki defini nan pwochen seksyon an, konekte, ki te swiv pa anviwònman kachèt.

kòd script

# 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

Mete kanpe konpresyon NGINX

Konpresyon kontni sou vole anvan ou voye li bay kliyan se yon bon fason pou amelyore pèfòmans sit, men sèlman si konpresyon konfigirasyon kòrèkteman. Seksyon sa a nan script la baze sou anviwònman yo kon sa.

kòd script

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

Mete kanpe NGINX pou WordPress

Apre sa, script la kreye yon dosye konfigirasyon pou WordPress default.conf nan katalòg la konf. d. Isit la li se konfigirasyon:

  • Aktive sètifika TLS yo resevwa nan men Let's Encrypt via Certbot (konfigirasyon li pral nan pwochen seksyon an)
  • Konfigure paramèt sekirite TLS ki baze sou rekòmandasyon ki soti nan Let's Encrypt
  • Pèmèt kachèt demann sote pou 1 èdtan pa default
  • Enfim anrejistreman aksè, osi byen ke anrejistreman erè si yo pa jwenn dosye a, pou de fichye yo mande yo: favicon.ico ak robots.txt
  • Refize aksè nan dosye kache ak kèk dosye phppou anpeche aksè ilegal oswa lansman envolontè
  • Enfim antre aksè pou fichye estatik ak font
  • Mete tit la Aksè-Kontwòl-Pèmèt-Orijin pou dosye font
  • Ajoute routage pou index.php ak lòt statistik.

kòd script

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

Konfigirasyon Certbot pou Sètifika ann ankripte epi renouvle yo otomatikman

Certbot se yon zouti gratis ki soti nan Electronic Frontier Foundation (EFF) ki pèmèt ou jwenn ak renouvle otomatikman sètifika TLS nan men Let's Encrypt. Script la fè etap sa yo pou konfigirasyon Certbot pou trete sètifika ki soti nan Let's Encrypt nan NGINX:

  • Sispann NGINX
  • Telechajman yo rekòmande paramèt TLS yo
  • Kouri Certbot pou jwenn sètifika pou sit la
  • Rekòmanse NGINX pou itilize sètifika
  • Konfigure Certbot pou kouri chak jou a 3:24 a.m. pou tcheke renouvèlman sètifika yo epi, si sa nesesè, telechaje nouvo sètifika epi rekòmanse NGINX.

kòd script

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

Lòt personnalisation nan sit ou a

Nou te pale pi wo a sou fason script nou an configure NGINX ak NGINX Unit pou sèvi yon sit entènèt ki pare pou pwodiksyon ak TLSSSL pèmèt. Ou kapab tou, selon bezwen ou, ajoute nan lavni:

  • Sipò Brotli, amelyore konpresyon sou-a-vole sou HTTPS
  • Mod Sekirite с règ pou WordPresspou anpeche atak otomatik sou sit ou a
  • Backup pou WordPress, apwopriye pou ou
  • Pwoteksyon avèk èd la AppArmor (sou Ubuntu)
  • Postfix oswa msmtp pou WordPress ka voye lapòs
  • Tcheke sit ou a pou w konprann konbyen trafik li ka okipe

Pou menm pi bon pèfòmans sit, nou rekòmande pou ajou NGINX Plus, pwodwi komèsyal antrepwiz nou an ki baze sou sous louvri NGINX. Abonnés li yo pral resevwa yon modil Brotli ki chaje dinamik, osi byen ke (pou yon frè adisyonèl) NGINX ModSecurity WAF. Nou ofri tou Pwoteje aplikasyon NGINX, yon modil WAF pou NGINX Plus ki baze sou teknoloji sekirite ki mennen nan endistri ki soti nan F5.

NB Pou sipò nan yon sit entènèt ki gen gwo chaj, ou ka kontakte espesyalis pon sid. Nou pral asire operasyon rapid ak serye nan sit entènèt ou oswa sèvis anba nenpòt chaj.

Sous: www.habr.com