Suiteáil WordPress a uathoibriú le hAonad NGINX agus Ubuntu

Suiteáil WordPress a uathoibriú le hAonad NGINX agus Ubuntu

Tá go leor ábhar amuigh ansin maidir le WordPress a shuiteáil; gheobhaidh cuardach Google do “WordPress install” thart ar leathmhilliún toradh. Mar sin féin, níl ach fíorbheagán treoracha úsáideacha amuigh ansin a chabhróidh leat WordPress agus an córas oibriúcháin bunúsach a shuiteáil agus a chumrú ionas gur féidir tacú leo thar thréimhse fada ama. B'fhéidir go mbraitheann na socruithe cearta go mór ar do riachtanais shonracha, nó d'fhéadfadh sé a bheith mar go ndéanann an míniú mionsonraithe an t-alt deacair a léamh.

San Airteagal seo, déanfaimid iarracht an chuid is fearr den dá shaol a chur le chéile trí script bash a sholáthar chun WordPress a shuiteáil go huathoibríoch ar Ubuntu, agus siúlfaimid tríd, ag míniú cad a dhéanann gach píosa agus na comhbhabhtálacha a rinneamar i ndearadh é. Má tá tú i d'úsáideoir taithí, is féidir leat skip an téacs an ailt agus díreach tóg an script le haghaidh modhnú agus úsáid i do thimpeallachtaí. Is é aschur na scripte suiteáil WordPress saincheaptha le tacaíocht Lets Encrypt, ag rith ar Aonad NGINX agus oiriúnach le haghaidh úsáid thionsclaíoch.

Déantar cur síos ar an ailtireacht fhorbartha chun WordPress a imscaradh ag baint úsáide as Aonad NGINX alt níos sine, déanfaimid a thuilleadh a chumrú anois freisin ar rudaí nár clúdaíodh ansin (mar atá i go leor ranganna teagaisc eile):

  • WordPress CLI
  • Déanaimis Criptigh agus teastais TLSSSL
  • Deimhniú a athnuachan go huathoibríoch
  • Taisce NGINX
  • Comhbhrú NGINX
  • Tacaíocht HTTPS agus HTTP/2
  • Uathoibriú próisis

Cuirfidh an t-alt síos ar shuiteáil ar fhreastalaí amháin, a dhéanfaidh freastalaí próiseála statach, freastalaí próiseála PHP, agus bunachar sonraí a óstáil ag an am céanna. Is ábhar féideartha don todhchaí é suiteáil le tacaíocht d’óstaigh agus seirbhísí fíorúla iolracha. Más mian leat go scríobhfaimid faoi rud éigin nach bhfuil sna hailt seo, scríobh sna tuairimí.

Riachtanais

  • Coimeádán freastalaí (LXCLXD), meaisín fíorúil, nó freastalaí crua-earraí rialta, a bhfuil ar a laghad 512MB de RAM agus Ubuntu 18.04 nó níos déanaí suiteáilte.
  • Calafoirt 80 agus 443 inrochtana ar an Idirlíon
  • An t-ainm fearainn a bhaineann le seoladh IP poiblí an fhreastalaí seo
  • Rochtain le cearta fréimhe (sudo).

Forbhreathnú ar ailtireacht

Tá an ailtireacht mar an gcéanna a thuairiscítear níos luaithe, feidhmchlár gréasáin trí shraith. Tá sé comhdhéanta de scripteanna PHP a fhorghníomhaítear ar an inneall PHP agus comhaid statacha arna bpróiseáil ag an bhfreastalaí gréasáin.

Suiteáil WordPress a uathoibriú le hAonad NGINX agus Ubuntu

Prionsabail ghinearálta

  • Tá go leor orduithe cumraíochta i script fillte isteach má tá coinníollacha le haghaidh díothachta: is féidir an script a rith go minic gan an baol go n-athrófar socruithe atá réidh cheana féin.
  • Déanann an script iarracht bogearraí ó stórtha a shuiteáil, ionas gur féidir leat nuashonruithe córais a chur i bhfeidhm in aon ordú amháin (apt upgrade le haghaidh Ubuntu).
  • Déanann foirne iarracht a bhrath go bhfuil siad ag rith i gcoimeádán ionas gur féidir leo a gcuid socruithe a athrú dá réir.
  • D'fhonn líon na bpróiseas snáithe atá le seoladh sna socruithe a shocrú, déanann an script iarracht na socruithe uathoibríocha le haghaidh oibriú i gcoimeádáin, meaisíní fíorúla agus freastalaithe crua-earraí a thomhas.
  • Nuair a dhéanaimid cur síos ar shocruithe, smaoinímid i gcónaí ar uathoibriú ar dtús, agus tá súil againn go mbeidh sé mar bhunús le do bhonneagar féin a chruthú mar chód.
  • Reáchtáiltear gach ordú ón úsáideoir root, toisc go n-athraíonn siad socruithe an chórais bhunúsacha, ach ritheann WordPress féin mar úsáideoir rialta.

Athróga timpeallachta a shocrú

Socraigh na hathróga timpeallachta seo a leanas sula ritheann tú an script:

  • WORDPRESS_DB_PASSWORD - Pasfhocal bunachar sonraí WordPress
  • WORDPRESS_ADMIN_USER - Ainm úsáideora admin WordPress
  • WORDPRESS_ADMIN_PASSWORD - Pasfhocal admin WordPress
  • WORDPRESS_ADMIN_EMAIL - Ríomhphost admin WordPress
  • WORDPRESS_URL – URL iomlán an tsuímh WordPress, ag tosú le https://.
  • LETS_ENCRYPT_STAGING — folamh de réir réamhshocraithe, ach tríd an luach a shocrú go 1, úsáidfidh tú freastalaithe stáitse Let's Encrypt, atá riachtanach chun teastais a iarraidh go minic agus do shocruithe á thástáil, nó d'fhéadfadh Let's Encrypt do sheoladh IP a bhlocáil go sealadach mar gheall ar an líon mór iarratas.

Seiceálann an script go bhfuil na hathróga seo a bhaineann le WordPress socraithe agus scoireann siad mura bhfuil siad.
Seiceáil línte script 572-576 an luach LETS_ENCRYPT_STAGING.

Athróga timpeallachta díorthaithe a shocrú

Socraíonn an script ar línte 55-61 na hathróga timpeallachta seo a leanas, go dtí luach códaithe éigin nó ag baint úsáide as luach díorthaithe ó na hathróga a socraíodh sa chuid roimhe seo:

  • DEBIAN_FRONTEND="noninteractive" — a insíonn d’fheidhmchláir go bhfuil siad ag rith i script agus nach bhfuil aon seans ann go mbeidh idirghníomhaíocht úsáideora ann.
  • WORDPRESS_CLI_VERSION="2.4.0" — Leagan WordPress CLI den fheidhmchlár.
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" — seiceálacha an chomhaid inrite WordPress CLI 2.4.0 (léirítear an leagan san athróg WORDPRESS_CLI_VERSION). Úsáideann an script ar líne 162 an luach seo chun a fhíorú gur íoslódáladh an comhad ceart WordPress CLI.
  • UPLOAD_MAX_FILESIZE="16M" — an méid comhaid uasta is féidir a uaslódáil chuig WordPress. Úsáidtear an socrú seo in áiteanna éagsúla, mar sin tá sé níos éasca é a shocrú in aon áit amháin.
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)" — óstainm córais, a bhaintear as an athróg WORDPRESS_URL. Úsáidtear é chun teastais TLS/SSL cuí a fháil ó Let's Encrypt, chomh maith le haghaidh fíorú inmheánach WordPress.
  • NGINX_CONF_DIR="/etc/nginx" - cosán chuig an eolaire le socruithe NGINX, lena n-áirítear an príomhchomhad nginx.conf.
  • CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}" - cosán chuig deimhnithe Let's Encrypt don láithreán WordPress, a fhaightear ón athróg TLS_HOSTNAME.

Óstainm a shannadh do fhreastalaí WordPress

Socraíonn an script óstainm an fhreastalaí ionas go mbeidh an luach ag teacht le hainm fearainn an tsuímh. Níl sé seo riachtanach, ach tá sé níos áisiúla ríomhphost amach a sheoladh trí SMTP agus freastalaí amháin á shocrú, mar atá cumraithe ag an script.

có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

Ag cur óstainm le /etc/hosts

Suimiú WP- Cron a úsáidtear chun tascanna tréimhsiúla a rith, éilíonn WordPress a bheith in ann rochtain a fháil air féin trí HTTP. Chun a chinntiú go n-oibríonn WP-Cron i gceart i ngach timpeallacht, cuireann an script líne leis an gcomhad / Srl / ina hóstachionas gur féidir le WordPress rochtain a fháil air féin tríd an gcomhéadan loopback:

có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

Suiteáil na huirlisí is gá le haghaidh céimeanna ina dhiaidh sin

Éilíonn an chuid eile den script roinnt clár agus glactar leis go bhfuil na stórtha cothrom le dáta. Nuashonraímid liosta na stórtha, agus ansin suiteáilimid na huirlisí riachtanacha:

có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

Ag cur an tAonad NGINX agus stórtha NGINX leis

Suiteálann an script Aonad NGINX agus foinse oscailte NGINX ó stórtha oifigiúla NGINX chun a chinntiú go n-úsáidtear na leaganacha leis na nuashonruithe slándála is déanaí agus na socruithe fabhtanna.

Cuireann an script stór an Aonaid NGINX agus ansin an stór NGINX, ag cur eochair na stórtha agus comhaid socruithe leis apt, rochtain ar stórtha tríd an Idirlíon a shainiú.

Tarlaíonn suiteáil iarbhír an Aonaid NGINX agus NGINX sa chéad chuid eile. Déanaimid stórtha a réamhchur chun meiteashonraí a nuashonrú go minic a sheachaint, rud a fhágann go mbeidh an tsuiteáil níos tapúla.

có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

Suiteáil NGINX, Aonad NGINX, PHP MariaDB, Certbot (Déanaimis Criptigh) agus a gcuid spleáchais

Nuair a chuirtear na stórtha go léir leis, déanaimid na meiteashonraí a nuashonrú agus na feidhmchláir a shuiteáil. Áiríonn na pacáistí atá suiteáilte ag an script síntí PHP a mholtar nuair a bhíonn WordPress.org á rith

có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

PHP a bhunú le húsáid le NGINX Unit agus WordPress

Cruthaíonn an script comhad socruithe san eolaire conf.d. Socraíonn sé seo an t-uasmhéid uaslódáil comhad le haghaidh PHP, cuireann sé ar chumas earráidí PHP a aschur go STDERR ionas go mbeidh siad logáilte chuig Aonad NGINX, agus atosóidh sé an tAonad NGINX.

có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

Ag socrú Socruithe Bunachar Sonraí MariaDB do WordPress

Roghnaigh muid MariaDB thar MySQL toisc go bhfuil níos mó gníomhaíochta pobail aige agus is féidir leis freisin soláthraíonn sé feidhmíocht níos fearr de réir réamhshocraithe (Is dócha, tá gach rud níos simplí anseo: chun MySQL a shuiteáil, ní mór duit stór eile a chur leis, thart. aistritheoir).

Cruthaíonn an script bunachar sonraí nua agus cruthaítear dintiúir rochtana WordPress tríd an gcomhéadan loopback:

có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;"

Suiteáil an clár WordPress CLI

Ag an gcéim seo suiteálann an script an clár WP-CLI. Leis, is féidir leat socruithe WordPress a shuiteáil agus a bhainistiú gan a bheith ort comhaid a chur in eagar de láimh, an bunachar sonraí a nuashonrú nó logáil isteach sa phainéal rialaithe. Is féidir é a úsáid freisin chun téamaí agus breiseáin a shuiteáil agus chun WordPress a nuashonrú.

có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

WordPress a shuiteáil agus a chumrú

Suiteálann an script an leagan is déanaí de WordPress san eolaire /var/www/wordpress, agus freisin athraíonn sé na socruithe:

  • Oibríonn an nasc bunachar sonraí thar soicéad fearainn unix in ionad TCP ar loopback chun trácht TCP a laghdú.
  • Cuireann WordPress réimír leis https:// chuig an URL má nascann cliaint le NGINX thar HTTPS, agus cuireann sé an t-óstainm iargúlta (mar a sholáthraíonn NGINX) chuig PHP freisin. Bainimid úsáid as píosa cód chun é seo a shocrú.
  • Teastaíonn HTTPS le WordPress chun logáil isteach
  • Tá struchtúr URL bunaithe ar acmhainní go ciúin
  • Socraítear ceadanna córas comhaid cearta don eolaire WordPress.

có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

Aonad NGINX a shocrú

Cumraíonn an script Aonad NGINX chun PHP a rith agus cosáin WordPress a láimhseáil, ag leithlisiú ainmspás na bpróiseas PHP agus ag uasmhéadú socruithe feidhmíochta. Tá trí ghné ann ar fiú aird a thabhairt orthu:

  • Cinntear tacaíocht ainmspás de réir an choinníll, bunaithe ar sheiceáil go bhfuil an script ag rith sa choimeádán. Tá sé seo riachtanach mar ní thacaíonn formhór na socruithe coimeádán le reáchtáil neadaithe coimeádán.
  • Má tá tacaíocht d'ainmspásanna, díchumasaítear an t-ainmspás líonra. Tá sé seo riachtanach chun ligean do WordPress nascadh go comhuaineach le críochphointí agus a bheith inrochtana ar an Idirlíon.
  • Socraítear uaslíon na bpróiseas mar seo a leanas: (Cuimhne ar fáil chun MariaDB agus NGINX Uniy a rith) / (teorainn RAM i PHP + 5)
    Tá an luach seo socraithe i socruithe an Aonaid NGINX.

Tugann an luach seo le tuiscint freisin go bhfuil ar a laghad dhá phróiseas PHP ar siúl i gcónaí, rud atá tábhachtach toisc go ndéanann WordPress go leor iarratas asincrónach dó féin, agus gan próisis bhreise a reáchtáil, mar shampla, brisfidh WP-Cron. B'fhéidir gur mhaith leat na teorainneacha seo a mhéadú nó a laghdú bunaithe ar do shocruithe áitiúla, toisc go bhfuil na socruithe a chruthaítear anseo coimeádach. Ar fhormhór na gcóras táirgthe tá na socruithe idir 10 agus 100.

có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

NGINX a shocrú

Socruithe Bunúsacha NGINX a chumrú

Cruthaíonn an script eolaire don taisce NGINX agus ansin cruthaíonn sé an príomhchomhad cumraíochta nginx.conf. Tabhair aird ar líon na bpróiseas láimhseála agus ar an socrú méid uasta comhaid le híoslódáil. Tá líne ann freisin ar a bhfuil an comhad socruithe comhbhrú, a shainmhínítear sa chéad chuid eile, ceangailte, agus socruithe taisce ina dhiaidh sin.

có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

Comhbhrú NGINX a shocrú

Is bealach iontach é ábhar a chomhbhrú ar an eitilt roimh é a sheoladh chuig cliaint chun feidhmíocht an tsuímh a fheabhsú, ach amháin má tá an comhbhrú cumraithe i gceart. Tá an chuid seo den script bunaithe ar na socruithe dá bhrí sin.

có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

Socrú NGINX do WordPress

Ansin, cruthaíonn an script comhad cumraíochta do WordPress réamhshocraithe.conf sa chatalóg conf.d. Anseo tá sé cumraithe:

  • Teastais TLS faighte ó Let's Encrypt trí Certbot a ghníomhachtú (beidh sé sa chéad chuid eile chun é a chumrú)
  • Cumraigh socruithe slándála TLS bunaithe ar mholtaí ó Let's Encrypt
  • Cumasaigh taisceadh iarratais scipeála ar feadh 1 uair an chloig de réir réamhshocraithe
  • Díchumasaigh logáil rochtana, chomh maith le logáil earráide mura bhfuarthas an comhad, le haghaidh dhá chomhad iarrtha coitianta: favicon.ico agus robots.txt
  • Diúltaigh rochtain ar chomhaid fholaithe agus ar roinnt comhad . Phprochtain mhídhleathach nó seoladh neamhbheartaithe a chosc
  • Díchumasaigh logáil rochtana do chomhaid statacha agus chló
  • An teideal a shocrú Rochtain-Rialú-Ceadaigh-Origin le haghaidh comhaid chló
  • Ag cur ródú le haghaidh index.php agus statach eile.

có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

Certbot a chumrú le haghaidh deimhnithe Let's Encrypt agus iad a athnuachan go huathoibríoch

Certbot Is uirlis saor in aisce é ón Electronic Frontier Foundation (EFF) a ligeann duit teastais TLS a fháil agus a athnuachan go huathoibríoch ó Let's Encrypt. Déanann an script na céimeanna seo a leanas chun Certbot a chumrú chun teastais a phróiseáil ó Let's Encrypt in NGINX:

  • Stopann NGINX
  • Íoslódáil socruithe molta TLS
  • Ritheann Certbot chun teastais a fháil don suíomh
  • Atosaíonn NGINX chun teastais a úsáid
  • Cumraigh Certbot a rith go laethúil ag 3:24 am chun seiceáil le haghaidh athnuachan teastais agus, más gá, teastais nua a íoslódáil agus NGINX a atosú.

có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

Saincheapadh breise ar do shuíomh

Labhair muid thuas faoi conas a chumraíonn ár script Aonad NGINX agus NGINX chun freastal ar shuíomh Gréasáin réidh le haghaidh táirgeadh le TLSSSL cumasaithe. Féadfaidh tú freisin, ag brath ar do chuid riachtanas, cur leis amach anseo:

  • Tacaíocht Brotli, comhbhrú feabhsaithe ar an eitilt thar HTTPS
  • ModSecurity с rialacha le haghaidh WordPresschun ionsaithe uathoibrithe ar do shuíomh a chosc
  • Cúltaca le haghaidh WordPress, oiriúnach duit
  • Cosaint leis an gcabhair AppArmor (ar Ubuntu)
  • Postfix nó msmtp ionas gur féidir le WordPress ríomhphost a sheoladh
  • Ag seiceáil do shuíomh ionas go dtuigeann tú cé mhéad tráchta is féidir leis a láimhseáil

Ar mhaithe le feidhmíocht suímh níos fearr fós, molaimid uasghrádú go NGINX Plus, ár dtáirge tráchtála de ghrád fiontair atá bunaithe ar fhoinse oscailte NGINX. Gheobhaidh a shíntiúsóirí modúl Brotli luchtaithe go dinimiciúil, chomh maith le (ar tháille bhreise) NGINX ModSecurity WAF. Cuirimid freisin NGINX App Protect, modúl WAF do NGINX Plus bunaithe ar theicneolaíocht slándála atá i gceannas ar an tionscal ó F5.

NB Chun tacaíocht a thabhairt do shuíomh Gréasáin ard-ualach, is féidir leat teagmháil a dhéanamh le speisialtóirí Southbridge. Cinnteoimid oibriú tapa agus iontaofa do shuíomh Gréasáin nó do sheirbhís faoi aon ualach.

Foinse: will.com