
Maraming mga materyales sa pag-install na magagamit. WordPress, paghahanap sa Google para sa mga keyword "WordPress "install" ay magbabalik ng halos kalahating milyong resulta. Gayunpaman, sa mga ito, kakaunti lang talaga ang mga kapaki-pakinabang na gabay para sa pag-install at pag-configure WordPress at ang pinagbabatayang operating system upang masuportahan ang mga ito sa mahabang panahon. Marahil ang mga tamang setting ay lubos na nakadepende sa mga partikular na pangangailangan, o marahil ito ay dahil ang detalyadong paliwanag ay nagpapahirap basahin ang artikulo.
Sa artikulong ito, susubukan naming pagsamahin ang pinakamahusay sa parehong pamamaraan sa pamamagitan ng pagbibigay ng bash script para sa awtomatikong pag-install. WordPress sa UbuntuTatalakayin din natin ito, ipapaliwanag kung ano ang ginagawa ng bawat piraso at ang mga kompromisong ginawa natin sa pagbuo nito. Kung ikaw ay isang bihasang gumagamit, maaari mong laktawan ang teksto at para sa pagbabago at paggamit sa iyong mga kapaligiran. Ang output ng script ay isang pasadyang instalasyon. WordPress may suporta sa Let's Encrypt, tumatakbo sa NGINX Unit at angkop para sa paggamit sa produksyon.
Binuo na arkitektura para sa pag-deploy WordPress Ang paggamit ng NGINX Unit ay inilarawan sa , ngayon ay higit pa nating i-configure ang mga bagay na hindi sakop doon (tulad ng sa maraming iba pang mga tutorial):
- WordPress CLI
- Let's Encrypt at TLSSSL Certificates
- Awtomatikong pag-renew ng mga sertipiko
- NGINX caching
- NGINX Compression
- Suporta sa HTTPS at HTTP/2
- I-proseso ang pag-aautomat
Ilalarawan ng artikulo ang pag-install sa isang server, na sabay-sabay na magho-host ng static processing server, PHP processing server, at database. Ang isang pag-install na sumusuporta sa maramihang mga virtual host at serbisyo ay isang potensyal na paksa para sa hinaharap. Kung gusto mong magsulat kami tungkol sa isang bagay na wala sa mga artikulong ito, sumulat sa mga komento.
Kinakailangan sa
- Server ng container ( o ), isang virtual machine, o isang regular na hardware server, na may hindi bababa sa 512 MB ng RAM at naka-install Ubuntu 18.04 o mas bago.
- Internet accessible port 80 at 443
- Domain name na nauugnay sa pampublikong ip address ng server na ito
- Pag-access sa ugat (sudo).
Pangkalahatang-ideya ng arkitektura
Ang arkitektura ay pareho sa inilarawan , isang three-tier na web application. Binubuo ito ng mga PHP script na tumatakbo sa PHP engine at mga static na file na pinoproseso ng web server.

Pangkalahatang mga prinsipyo
- Maraming configuration command sa isang script ang nakabalot kung ang mga kundisyon para sa idempotency: ang script ay maaaring patakbuhin nang maraming beses nang walang panganib na baguhin ang mga setting na nasa lugar na.
- Sinusubukan ng script na mag-install ng software mula sa mga repository, para mailapat mo ang mga update sa system sa isang command (
apt upgradepara sa Ubuntu). - Sinusubukan ng mga command na tuklasin na tumatakbo ang mga ito sa isang lalagyan upang mabago nila ang kanilang mga setting nang naaayon.
- Upang maitakda ang bilang ng mga proseso ng thread na magsisimula sa mga setting, sinusubukan ng script na hulaan ang mga awtomatikong setting para sa pagtatrabaho sa mga container, virtual machine, at hardware server.
- Kapag naglalarawan ng mga setting, lagi naming iniisip muna ang tungkol sa automation, na, inaasahan namin, ay magiging batayan para sa paglikha ng iyong sariling imprastraktura bilang code.
- Ang lahat ng mga utos ay pinapatakbo bilang gumagamit ugat, dahil binabago nila ang mga pangunahing setting ng system, ngunit direkta WordPress gumagana mula sa isang regular na gumagamit.
Pagtatakda ng mga variable ng kapaligiran
Itakda ang mga sumusunod na variable ng kapaligiran bago patakbuhin ang script:
WORDPRESS_DB_PASSWORD— password sa database WordPressWORDPRESS_ADMIN_USER— pangalan ng administrador WordPressWORDPRESS_ADMIN_PASSWORD— password ng administrador WordPressWORDPRESS_ADMIN_EMAIL— email ng administrador WordPressWORDPRESS_URL— buong URL ng website WordPressSimula mula sahttps://.LETS_ENCRYPT_STAGING- walang laman bilang default, ngunit sa pamamagitan ng pagtatakda ng value sa 1, gagamitin mo ang mga staging server ng Let's Encrypt, na kinakailangan para sa madalas na paghiling ng mga certificate kapag sinusubok ang iyong mga setting, kung hindi, maaaring pansamantalang i-block ng Let's Encrypt ang iyong ip address dahil sa malaking bilang ng mga kahilingan .
Sinusuri ng script na ang mga kaugnay na ito WordPress Ang mga variable ay nakatakda, at lalabas kung hindi.
Mga linya ng script 572-576 suriin ang halaga LETS_ENCRYPT_STAGING.
Pagtatakda ng mga nagmula na variable ng kapaligiran
Ang script sa mga linya 55-61 ay nagtatakda ng mga sumusunod na variable ng kapaligiran, alinman sa ilang hard-coded na halaga o gamit ang isang halaga na nakuha mula sa mga variable na itinakda sa nakaraang seksyon:
DEBIAN_FRONTEND="noninteractive"- Sinasabi sa mga application na tumatakbo ang mga ito sa isang script at walang posibilidad ng pakikipag-ugnayan ng user.WORDPRESS_CLI_VERSION="2.4.0"— bersyon ng aplikasyon WordPress CLI.WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c"— checksum ng executable file WordPress Ang CLI 2.4.0 (ang bersyon ay tinukoy sa variableWORDPRESS_CLI_VERSION). Ginagamit ng script sa linya 162 ang halagang ito upang suriin kung ang tamang file ay na-download. WordPress CLI.UPLOAD_MAX_FILESIZE="16M"— ang pinakamataas na laki ng file na maaaring i-upload WordPressGinagamit ang setting na ito sa ilang lugar, kaya mas madaling itakda ito sa isang lugar.TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)"— ang hostname ng sistema, na kinuha mula sa variable na WORDPRESS_URL. Ginagamit upang makuha ang naaangkop na mga sertipiko ng TLS/SSL mula sa Let's Encrypt, pati na rin para sa panloob na beripikasyon. WordPress.NGINX_CONF_DIR="/etc/nginx"- landas sa direktoryo na may mga setting ng NGINX, kasama ang pangunahing filenginx.conf.CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}"— landas patungo sa mga sertipiko ng Let's Encrypt para sa site WordPress, nakuha mula sa isang baryabolTLS_HOSTNAME.
Pagtatalaga ng pangalan ng host WordPress tagapagsilbi
Itinatakda ng script ang hostname ng server upang tumugma sa domain name ng site. Hindi ito kinakailangan, ngunit mas maginhawang magpadala ng papalabas na mail sa pamamagitan ng SMTP kapag nagse-set up ng iisang server, gaya ng na-configure ng script.
script code
# 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}"
fiPagdaragdag ng hostname sa /etc/hosts
Dagdag ginagamit upang magpatakbo ng mga pana-panahong gawain, ay nangangailangan na WordPress maaaring ma-access ang sarili nito sa pamamagitan ng HTTP. Upang matiyak na gumagana nang tama ang WP-Cron sa lahat ng kapaligiran, nagdadagdag ang script ng isang linya sa file / Etc / host, kaya WordPress maaaring ma-access ang sarili nito sa pamamagitan ng loopback interface:
script code
# 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
fiPag-install ng mga tool na kinakailangan para sa mga susunod na hakbang
Ang natitirang bahagi ng script ay nangangailangan ng ilang mga programa at ipinapalagay na ang mga repositoryo ay napapanahon. Ina-update namin ang listahan ng mga repositoryo, pagkatapos ay i-install namin ang mga kinakailangang tool:
script code
# 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-releasePagdaragdag ng NGINX Unit at NGINX Repositories
Ini-install ng script ang NGINX Unit at open source NGINX mula sa opisyal na mga repository ng NGINX upang matiyak na ang mga bersyon na may pinakabagong mga patch sa seguridad at pag-aayos ng bug ay ginagamit.
Ang script ay nagdaragdag ng NGINX Unit repository at pagkatapos ay ang NGINX repository, pagdaragdag ng mga repositoryo key at configuration file apt, na tumutukoy sa pag-access sa mga repositoryo sa pamamagitan ng Internet.
Ang aktwal na pag-install ng NGINX Unit at NGINX ay nangyayari sa susunod na seksyon. Paunang idinaragdag namin ang mga repositoryo para hindi namin kailangang i-update ang metadata nang maraming beses, na nagpapabilis sa pag-install.
script code
# 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
fiPag-install ng NGINX, NGINX Unit, PHP MariaDB, Certbot (Let's Encrypt) at ang kanilang mga dependency
Kapag naidagdag na ang lahat ng repository, ia-update namin ang metadata at i-install ang mga application. Kasama rin sa mga package na ini-install ng script ang mga PHP extension na inirerekomenda sa startup. WordPress. Org
script code
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-serverPag-configure ng PHP para magamit sa NGINX Unit at WordPress
Lumilikha ang script ng file ng mga setting sa direktoryo conf.d. Itinatakda nito ang maximum na laki para sa mga pag-upload ng PHP, ino-on ang output ng error sa PHP sa STDERR upang maisulat ang mga ito sa log ng NGINX Unit, at i-restart ang NGINX Unit.
script code
# 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 restartPag-set up ng mga setting ng database ng MariaDB para sa WordPress
Pinili namin ang MariaDB kaysa sa MySQL dahil mas marami itong aktibidad sa komunidad at malamang (marahil, ang lahat ay mas simple dito: upang mai-install ang MySQL, kailangan mong magdagdag ng isa pang imbakan, tinatayang. tagasalin).
Ang script ay lilikha ng isang bagong database at lilikha ng mga kredensyal sa pag-access. WordPress sa pamamagitan ng loopback interface:
script code
# 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;"Pag-install ng programa WordPress CLI
Sa hakbang na ito, ini-install ng script ang program Sa tulong nito, maaari mong itakda at pamahalaan ang mga setting WordPress nang hindi kinakailangang manu-manong i-edit ang mga file, i-update ang database, o mag-log in sa control panel. Maaari rin itong gamitin upang mag-install ng mga tema at add-on at magsagawa ng mga update. WordPress.
script code
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
fiPag-install at pagsasaayos WordPress
Ini-install ng script ang pinakabagong bersyon WordPress sa catalog /var/www/wordpressat binabago din ang mga setting:
- Gumagana ang koneksyon sa database sa unix domain socket sa halip na TCP sa loopback upang mabawasan ang trapiko ng TCP.
- WordPress nagdadagdag ng unlapi https:// sa URL kung kumonekta ang mga kliyente sa NGINX sa pamamagitan ng HTTPS, at ipinapadala rin ang remote hostname (tulad ng ibinigay ng NGINX) sa PHP. Gumagamit kami ng isang piraso ng code para i-set up ito.
- WordPress Kinakailangan ang HTTPS para makapag-log in
- Ang default na istraktura ng URL ay batay sa mga mapagkukunan
- Ang mga tamang pahintulot sa file system ay nakatakda para sa direktoryo. WordPress.
script code
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
fiPagse-set up ng NGINX Unit
Kino-configure ng script ang NGINX Unit upang patakbuhin ang PHP at pangasiwaan ang mga path. WordPress, paghihiwalay ng namespace ng proseso ng PHP at pag-optimize ng mga setting ng pagganap. May tatlong tampok na dapat tandaan:
- Ang suporta para sa mga namespace ay tinutukoy ng kundisyon, batay sa pagsuri na ang script ay tumatakbo sa isang container. Ito ay kinakailangan dahil karamihan sa mga setup ng container ay hindi sumusuporta sa nested launch ng mga container.
- Kung mayroong suporta para sa mga namespace, huwag paganahin ang namespace networkIto ay kinakailangan upang payagan ang WordPress sabay na kumonekta sa mga endpoint at maging maa-access sa Internet.
- Ang maximum na bilang ng mga proseso ay tinukoy bilang mga sumusunod: (Available memory para sa pagpapatakbo ng MariaDB at NGINX Uniy)/(RAM limit sa PHP + 5)
Nakatakda ang value na ito sa mga setting ng NGINX Unit.
Ipinahihiwatig din ng halagang ito na palaging mayroong hindi bababa sa dalawang proseso ng PHP na tumatakbo, na mahalaga dahil WordPress Gumagawa ito ng maraming asynchronous request sa sarili nito, at kung walang karagdagang proseso, ang pagpapatakbo, halimbawa, ng WP-Cron, ay mabibigo. Maaari mong dagdagan o bawasan ang mga limitasyong ito batay sa iyong mga lokal na setting, dahil ang mga setting na nilikha rito ay konserbatibo. Sa karamihan ng mga sistema ng produksyon, ang mga setting ay nasa pagitan ng 10 at 100.
script code
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/configPagse-set up ng NGINX
Pag-configure ng Mga Pangunahing Setting ng NGINX
Ang script ay lumilikha ng isang direktoryo para sa NGINX cache at pagkatapos ay lumilikha ng pangunahing configuration file nginx.conf. Bigyang-pansin ang bilang ng mga proseso ng handler at ang setting ng maximum na laki ng file para sa pag-upload. Mayroon ding isang linya na kasama ang file ng mga setting ng compression na tinukoy sa susunod na seksyon, na sinusundan ng mga setting ng caching.
script code
# 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;
}
EOMPagse-set up ng NGINX compression
Ang mabilisang pag-compress ng content bago ito ipadala sa mga kliyente ay isang mahusay na paraan para mapabuti ang performance ng site, ngunit kung tama lang ang pagkaka-configure ng compression. Ang seksyong ito ng script ay batay sa mga setting .
script code
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;
EOMPag-set up ng NGINX para sa WordPress
Susunod, ang script ay lilikha ng isang configuration file para sa WordPress default.conf sa catalog conf.d. Ito ay naka-configure dito:
- Ang pag-activate ng mga TLS certificate na natanggap mula sa Let's Encrypt sa pamamagitan ng Certbot (ang pag-set up nito ay nasa susunod na seksyon)
- Pag-configure ng mga setting ng seguridad ng TLS batay sa mga rekomendasyon mula sa Let's Encrypt
- Paganahin ang pag-cache ng mga kahilingan sa paglaktaw sa loob ng 1 oras bilang default
- Huwag paganahin ang pag-log sa pag-access, pati na rin ang pag-log ng error kung hindi nahanap ang file, para sa dalawang karaniwang hinihiling na file: favicon.ico at robots.txt
- Pigilan ang pag-access sa mga nakatagong file at ilang file Phpupang maiwasan ang ilegal na pag-access o hindi sinasadyang pagsisimula
- Huwag paganahin ang pag-log sa pag-access para sa mga static at font file
- Setting ng header para sa mga file ng font
- Pagdaragdag ng pagruruta para sa index.php at iba pang mga static.
script code
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;
}
}
EOMPagse-set up ng Certbot para sa mga certificate mula sa Let's Encrypt at awtomatikong i-renew ang mga ito
ay isang libreng tool mula sa Electronic Frontier Foundation (EFF) na nagbibigay-daan sa iyong makakuha at awtomatikong mag-renew ng mga TLS certificate mula sa Let's Encrypt. Ginagawa ng script ang sumusunod upang i-configure ang Certbot upang iproseso ang mga sertipiko mula sa Let's Encrypt sa NGINX:
- Itigil ang NGINX
- Nagda-download ng mga inirerekomendang setting ng TLS
- Pinapatakbo ang Certbot upang makakuha ng mga sertipiko para sa site
- I-restart ang NGINX para gumamit ng mga certificate
- Kino-configure ang Certbot na tumakbo araw-araw sa 3:24 AM upang tingnan kung kailangang i-renew ang mga certificate, at kung kinakailangan, mag-download ng mga bagong certificate at i-restart ang NGINX.
script code
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 -
fiKaragdagang pagpapasadya ng iyong site
Napag-usapan namin sa itaas kung paano kino-configure ng aming script ang NGINX at NGINX Unit upang maghatid ng isang production-ready na site na may naka-enable na TLSSSL. Maaari mo ring, depende sa iyong mga pangangailangan, magdagdag sa hinaharap:
- suporta , pinahusay na on-the-fly compression sa HTTPS
- с upang maiwasan ang mga awtomatikong pag-atake sa iyong site
- para sa WordPress, angkop para sa iyo
- sa tulong (sa Ubuntu)
- Postfix o msmtp papunta sa WordPress maaaring magpadala ng sulat
- Sinusuri ang iyong site upang maunawaan mo kung gaano karaming trapiko ang maaari nitong pangasiwaan
Para sa mas mahusay na pagganap ng site, inirerekomenda namin ang pag-upgrade sa , ang aming komersyal, enterprise-grade na produkto batay sa open source NGINX. Ang mga subscriber nito ay makakatanggap ng dynamic na na-load na Brotli module, pati na rin (para sa karagdagang bayad) . Nag-aalok din kami , isang WAF module para sa NGINX Plus batay sa teknolohiyang pangseguridad na nangunguna sa industriya mula sa F5.
NB Para sa suporta ng isang napaka-load na site, maaari kang makipag-ugnayan sa mga espesyalista . Sisiguraduhin namin ang mabilis at maaasahang operasyon ng iyong website o serbisyo sa ilalim ng anumang load.
Pinagmulan: www.habr.com
