
Ci sò parechji materiali d'installazione dispunibili. WordPress, Ricerca di parole chjave in Google "WordPress installà" restituirà circa mezu milione di risultati. Tuttavia, trà elli, ci sò in realtà assai poche guide utili per l'installazione è a cunfigurazione WordPress è u sistema operativu sottustante per ch'elli possinu esse supportati per un longu periodu di tempu. Forse i paràmetri curretti dipendenu assai da bisogni specifichi, o forse questu hè perchè a spiegazione dettagliata rende l'articulu difficiule da leghje.
In questu articulu, pruveremu à cumbinà u megliu di i dui approcci furnendu un script bash per l'installazione automatica. WordPress nantu UbuntuA faremu dinù una panoramica, spiegendu ciò chì face ogni pezzu è i compromessi chì avemu fattu in u so sviluppu. Sè vo site un utilizatore espertu, pudete saltà u testu è solu per a mudificazione è l'usu in i vostri ambienti. L'output di u script hè una installazione persunalizata. WordPress cù u supportu Let's Encrypt, chì funziona nantu à l'unità NGINX è hè adattatu per l'usu in pruduzzione.
Architettura sviluppata per u spiegamentu WordPress l'usu di l'unità NGINX hè descrittu in , avà avemu ancu cunfigurà ancu e cose chì ùn eranu micca cuparti quì (cum'è in parechji altri tutoriali):
- WordPress CLI
- Criptemu è i Certificati TLSSSL
- Rinuvamentu automaticu di certificati
- NGINX cache
- Cumpressione NGINX
- Supportu HTTPS è HTTP/2
- L'automatizazione di u prucessu
L'articulu descriverà a stallazione nantu à un servitore, chì ospitu simultaneamente un servitore di trattamentu staticu, un servitore di trasfurmazioni PHP è una basa di dati. Una stallazione chì sustene parechje host virtuale è servizii hè un tema potenziale per u futuru. Se vulete chì scrivitemu qualcosa chì ùn hè micca in questi articuli, scrivite in i cumenti.
esigenze
- servitore di container ( o ), una macchina virtuale, o un servitore hardware regulare, cù almenu 512 MB di RAM è installatu Ubuntu 18.04 o più tardi.
- Porti accessibili in Internet 80 è 443
- Nome di duminiu assuciatu cù l'indirizzu ip publicu di stu servitore
- Accessu root (sudo).
Panoramica di l'architettura
L'architettura hè u listessu cum'è descrittu , una applicazione web à trè livelli. Hè custituitu di script PHP chì funzionanu nantu à u mutore PHP è schedarii statici chì sò trattati da u servitore web.

Principii generichi
- Molti cumandamenti di cunfigurazione in un script sò impannillati in i cundizioni per l'idempotenza: u script pò esse eseguitu parechje volte senza u risicu di cambià i paràmetri chì sò digià in u locu.
- U script prova à stallà u software da i repositori, cusì pudete applicà l'aghjurnamenti di u sistema in un cumandamentu (
apt upgradedi Ubuntu). - I cumandamenti cercanu di detectà chì sò in esecuzione in un containeru per pudè cambià i so paràmetri in cunseguenza.
- Per stabilisce u numeru di prucessi di filu per inizià in i paràmetri, u script prova di indovinà i paràmetri automatici per travaglià in cuntenituri, macchine virtuali è servitori di hardware.
- Quandu si descrizanu i paràmetri, pensemu sempre prima di tuttu à l'automatizazione, chì, speremu, diventerà a basa per creà a vostra propria infrastruttura cum'è codice.
- Tutti i cumandamenti sò eseguiti cum'è utilizatore ràdica, perchè cambianu i paràmetri principali di u sistema, ma direttamente WordPress funziona da un utilizatore regulare.
Stabbilimentu di variabili di l'ambiente
Impostate e seguenti variabili d'ambiente prima di eseguisce u script:
WORDPRESS_DB_PASSWORD— password per a basa di dati WordPressWORDPRESS_ADMIN_USER— nome di l'amministratore WordPressWORDPRESS_ADMIN_PASSWORD— password di l'amministratore WordPressWORDPRESS_ADMIN_EMAIL— email di l'amministratore WordPressWORDPRESS_URL— URL cumpletu di u situ web WordPress, cuminciendu cùhttps://.LETS_ENCRYPT_STAGING- viotu per difettu, ma mettendu u valore à 1, aduprà i servitori di staging Let's Encrypt, chì sò necessarii per dumandà spessu certificati durante a prova di i vostri paràmetri, altrimenti Let's Encrypt pò bluccà temporaneamente u vostru indirizzu IP per un gran numaru di richieste. .
U script verifica chì questi sò ligati WordPress e variabili sò impostate, è esce altrimenti.
Linee di script 572-576 verificate u valore LETS_ENCRYPT_STAGING.
Stabbilimentu di variabili d'ambiente derivati
U script nantu à e linee 55-61 stabilisce e seguenti variabili di l'ambienti, sia à qualchì valore codificatu, sia utilizendu un valore ottenutu da e variàbili stabilite in a sezione precedente:
DEBIAN_FRONTEND="noninteractive"- Dice à l'applicazioni chì sò in esecuzione in un script è chì ùn ci hè micca pussibilità di interazzione cù l'utilizatori.WORDPRESS_CLI_VERSION="2.4.0"— versione di l'applicazione WordPress CLI.WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c"— somma di cuntrollu di u schedariu eseguibile WordPress CLI 2.4.0 (a versione hè specificata in a variabileWORDPRESS_CLI_VERSIONU script in a linea 162 usa stu valore per verificà chì u schedariu currettu hè statu telecaricatu. WordPress CLI.UPLOAD_MAX_FILESIZE="16M"— a dimensione massima di u schedariu chì pò esse caricatu WordPressQuesta impostazione hè aduprata in parechji lochi, dunque hè più faciule di cunfiguralla in un locu unicu.TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)"— u nome di l'ospite di u sistema, recuperatu da a variabile WORDPRESS_URL. Adupratu per ottene i certificati TLS/SSL adatti da Let's Encrypt, è ancu per a verificazione interna. WordPress.NGINX_CONF_DIR="/etc/nginx"- percorsu à u cartulare cù paràmetri NGINX, cumpresu u schedariu principalenginx.conf.CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}"— percorsu versu i certificati Let's Encrypt per u situ WordPress, ottenutu da una variabileTLS_HOSTNAME.
Assignazione di u nome di l'ospite WordPress servitore
U script stabilisce u nome d'ospite di u servitore per currisponde à u nome di duminiu di u situ. Questu ùn hè micca necessariu, ma hè più cunvene per mandà u mail in uscita via SMTP quandu stabilisce un servitore unicu, cum'è cunfiguratu da u script.
codice di scrittura
# 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}"
fiAghjunghje un nome di host à /etc/hosts
Supplemento adupratu per eseguisce attività periodiche, richiede chì WordPress puderia accede à sè stessu via HTTP. Per assicurà chì WP-Cron funziona currettamente in tutti l'ambienti, u script aghjusta una linea à u schedariu / etc / hosts, cusì WordPress pò accede à sè stessu via l'interfaccia di loopback:
codice di scrittura
# 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
fiStallà l'arnesi necessarii per i prossimi passi
U restu di u script hà bisognu di qualchi prugrammi è assume chì i repositori sò aghjurnati. Aghjurnà a lista di i repositori, dopu avè installatu l'arnesi necessarii:
codice di scrittura
# 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-releaseAghjunghjendu NGINX Unit è NGINX Repositories
U script installate NGINX Unit è open source NGINX da i repositori ufficiali NGINX per assicurà chì e versioni cù l'ultimi patch di sicurezza è correzioni di bug sò aduprate.
U script aghjunghjenu u repository NGINX Unit è dopu u repository NGINX, aghjunghjendu a chjave di repository è i schedarii di cunfigurazione apt, chì definisce l'accessu à i repositori via Internet.
L'installazione attuale di NGINX Unit è NGINX succede in a sezione dopu. Avemu pre-aghjunghje i repositori per ùn avè micca aghjurnà i metadati parechje volte, chì rende l'installazione più veloce.
codice di scrittura
# 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
fiInstallazione di NGINX, NGINX Unit, PHP MariaDB, Certbot (Let's Encrypt) è e so dipendenze
Una volta chì tutti i repositori sò aghjunti, aghjurnemu i metadati è installemu l'applicazioni. I pacchetti installati da u script includenu ancu estensioni PHP cunsigliate à l'avviu. WordPress.org
codice di scrittura
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-serverCunfigurazione di PHP per l'usu cù l'unità NGINX è WordPress
U script crea un schedariu di paràmetri in u cartulare conf. d. Questu stabilisce a dimensione massima per l'uploads di PHP, attiva l'output d'errore PHP in STDERR per esse scritti in u logu di l'Unità NGINX, è riavvia l'Unità NGINX.
codice di scrittura
# 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 restartConfigurazione di i paràmetri di a basa di dati MariaDB per WordPress
Avemu sceltu MariaDB nantu à MySQL postu chì hà più attività di a cumunità è hè ancu prubabile (prubabilmente, tuttu hè più simplice quì: per installà MySQL, avete bisognu di aghjunghje un altru repository, ca. traduttore).
U script crea una nova basa di dati è crea credenziali d'accessu. WordPress via l'interfaccia di loopback:
codice di scrittura
# 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;"Installazione di u prugramma WordPress CLI
À questu passu, u script installà u prugramma Cù u so aiutu pudete cunfigurà è gestisce i paràmetri WordPress senza avè bisognu di mudificà manualmente i fugliali, aghjurnà a basa di dati, o accede à u pannellu di cuntrollu. Pò ancu esse adupratu per installà temi è add-ons è fà aghjurnamenti. WordPress.
codice di scrittura
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
fiStallazione è cunfigurazione WordPress
U script installa l'ultima versione WordPress à u catalogu /var/www/wordpressè cambia ancu i paràmetri:
- A cunnessione di a basa di dati funziona nantu à un socket di duminiu Unix invece di TCP in loopback per riduce u trafficu TCP.
- WordPress aghjusta un prefissu https:// à l'URL se i clienti si cunnetta à NGINX per HTTPS, è ancu manda u nome d'ospitu remoto (cum'è furnitu da NGINX) à PHP. Avemu aduprà un pezzu di codice per stallà questu.
- WordPress HTTPS hè necessariu per cunnettassi
- A struttura URL predeterminata hè basatu annantu à e risorse
- I permessi di u sistema di fugliali curretti sò stabiliti per u cartulare. WordPress.
codice di scrittura
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}" --data-gt-translate-attributes='["title"]' 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
fiConfigurazione di l'unità NGINX
U script configura l'unità NGINX per eseguisce PHP è gestisce i percorsi. WordPress, isolendu u spaziu di nomi di u prucessu PHP è ottimizendu i paràmetri di prestazione. Ci sò trè caratteristiche chì valenu a pena nutà:
- U supportu per i namespaces hè determinatu da a cundizione, basatu annantu à verificà chì u script hè in esecuzione in un containeru. Questu hè necessariu perchè a maiò parte di e configurazioni di cuntenituri ùn sustene micca u lanciu nidificatu di cuntenituri.
- Se ci hè supportu per i namespaces, disattiveghjanu u namespace retaQuestu hè necessariu per permette WordPress cunnette si simultaneamente à i punti finali è esse accessibile in Internet.
- U numeru massimu di prucessi hè definitu cum'è seguita: (Memoria dispunibile per eseguisce MariaDB è NGINX Uniy)/(limite RAM in PHP + 5)
Stu valore hè stabilitu in i paràmetri di l'unità NGINX.
Stu valore implica ancu chì ci sò sempre almenu dui prucessi PHP in esecuzione, ciò chì hè impurtante perchè WordPress face assai richieste asincrone à sè stessu, è senza prucessi supplementari, l'esecuzione, per esempiu, WP-Cron, fallirà. Pudete vulè aumentà o diminuisce questi limiti secondu i vostri paràmetri lucali, postu chì i paràmetri creati quì sò cunservativi. In a maiò parte di i sistemi di pruduzzione, i paràmetri sò trà 10 è 100.
codice di scrittura
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/configConfigurazione di NGINX
Configurazione di i paràmetri basi di NGINX
U script crea un repertoriu per a cache NGINX è poi crea u schedariu di cunfigurazione principale nginx.conf. Prestate attenzione à u numeru di prucessi di gestione è l'impostazione di a dimensione massima di u schedariu per upload. Ci hè ancu una linea chì include u schedariu di paràmetri di compressione definitu in a sezione dopu, seguita da i paràmetri di caching.
codice di scrittura
# 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;
}
EOMConfigurazione di a compressione NGINX
Cumpressà u cuntenutu nantu à a mosca prima di mandà à i clienti hè una bella manera di migliurà u rendiment di u situ, ma solu se a compressione hè cunfigurata currettamente. Questa sezione di u script hè basatu annantu à i paràmetri .
codice di scrittura
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;
EOMCunfigurazione di NGINX per WordPress
Dopu, u script crea un schedariu di cunfigurazione per WordPress default.conf in u catalogu conf. d. Hè cunfiguratu quì:
- Attivà i certificati TLS ricevuti da Let's Encrypt via Certbot (l'installazione sarà in a sezione successiva)
- Configurazione di i paràmetri di sicurezza TLS basatu nantu à i cunsiglii di Let's Encrypt
- Per automaticamente, attivate e richieste di salta in cache per 1 ora
- Disattivate l'accessu di l'accessu, è ancu l'errore di logu se u schedariu ùn hè micca truvatu, per dui schedari cumuni cumuni: favicon.ico è robots.txt
- Impedisce l'accessu à i fugliali nascosti è à certi schedari .phpper impedisce l'accessu illegale o l'iniziu imprevisu
- Disattivate l'accessu di logu per i fugliali statichi è di font
- Impostazione di l'intestazione per i schedarii di font
- Aghjunghjendu routing per index.php è altre statics.
codice di scrittura
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;
}
}
EOMConfigurazione di Certbot per i certificati da Let's Encrypt è rinnuvà automaticamente
hè un strumentu gratuitu da a Electronic Frontier Foundation (EFF) chì permette di ottene è rinnuvà automaticamente i certificati TLS da Let's Encrypt. U script face i seguenti per cunfigurà Certbot per processà i certificati da Let's Encrypt in NGINX:
- Arresta NGINX
- Scarica i paràmetri TLS cunsigliatu
- Esegue Certbot per uttene certificati per u situ
- Riavvia NGINX per utilizà i certificati
- Configura Certbot per eseguisce ogni ghjornu à 3:24 AM per verificà se i certificati anu da esse rinnuvati, è se necessariu, scaricate novi certificati è riavvia NGINX.
codice di scrittura
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 -
fipersunalizazione supplementu di u vostru situ
Avemu parlatu sopra cumu u nostru script configura NGINX è NGINX Unit per serve un situ prontu per a produzzione cù TLSSSL attivatu. Pudete ancu, sicondu i vostri bisogni, aghjunghje in u futuru:
- sustegnu , Migliurà a compressione nantu à a mosca nantu à HTTPS
- с per prevene attacchi automatizati à u vostru situ
- di WordPress, adattatu per voi
- cun l'aiutu di (nantu à u Ubuntu)
- Postfix o msmtp à WordPress puderia mandà a posta
- Verificate u vostru situ per capisce quantu trafficu pò trattà
Per un rendimentu di u situ ancu megliu, ricumandemu l'aghjurnamentu à , u nostru pruduttu cummerciale, di qualità di l'impresa basatu annantu à NGINX open source. I so abbonati riceveranu un modulu Brotli caricatu dinamicamente, è ancu (per una tarifa supplementaria) . Avemu ancu prupostu , un modulu WAF per NGINX Plus basatu nantu à a tecnulugia di sicurità di punta di l'industria da F5.
NB Per u sustegnu di un situ assai caricatu, pudete cuntattate i specialisti . Assicureremu un funziunamentu veloce è affidabile di u vostru situ web o serviziu sottu ogni carica.
Source: www.habr.com
