使用 NGINX Unit 和 Ubuntu 自动安装 WordPress

使用 NGINX Unit 和 Ubuntu 自动安装 WordPress

有很多关于如何安装 WordPress 的教程,在 Google 上搜索“WordPress install”会出现大约 XNUMX 万个结果。 但实际上,其中很少有好的指南,可以根据这些指南安装和配置WordPress以及底层操作系统,使其能够长期支持。 也许正确的设置很大程度上取决于特定的需求,或者这是因为详细的解释使文章难以阅读。

在本文中,我们将尝试通过提供一个 bash 脚本在 Ubuntu 上自动安装 WordPress 来结合两全其美,并逐步介绍它,解释每个部分的作用,以及我们在开发它时所做的妥协。 如果您是高级用户,可以跳过文章正文,直接阅读 拿剧本 用于在您的环境中进行修改和使用。 该脚本的输出是一个自定义 WordPress 安装,支持 Lets Encrypt,在 NGINX Unit 上运行,适合生产使用。

使用 NGINX 单元部署 WordPress 的开发架构在 旧文章,现在我们还将进一步配置此处未涵盖的内容(如许多其他教程中一样):

  • WordPress命令行
  • 让我们加密和 TLSSSL 证书
  • 自动更新证书
  • NGINX 缓存
  • NGINX 压缩
  • HTTPS 和 HTTP/2 支持
  • 过程自动化

本文将描述在一台服务器上的安装,该服务器将同时托管静态处理服务器、PHP 处理服务器和数据库。 支持多个虚拟主机和服务的安装是未来的一个潜在主题。 如果您希望我们写一些这些文章中没有的内容,请在评论中写下。

需求

  • 容器服务器(LXC или LXD)、虚拟机或至少具有 512MB RAM 且安装了 Ubuntu 18.04 或更高版本的常规 Iron 服务器。
  • 可访问 Internet 的端口 80 和 443
  • 与该服务器的公共 IP 地址关联的域名
  • 根访问(sudo)。

架构概述

架构与描述的相同 早期,一个三层 Web 应用程序。 它由在 PHP 引擎上运行的 PHP 脚本和由 Web 服务器处理的静态文件组成。

使用 NGINX Unit 和 Ubuntu 自动安装 WordPress

一般原则

  • 脚本中的许多配置命令都包含在幂等性的 if 条件中:脚本可以多次运行,而不会存在更改已存在设置的风险。
  • 该脚本尝试从存储库安装软件,因此您可以通过一个命令应用系统更新(apt upgrade 对于 Ubuntu)。
  • 命令尝试检测它们是否在容器中运行,以便可以相应地更改其设置。
  • 为了在设置中设置要启动的线程进程数,该脚本尝试猜测在容器、虚拟机和硬件服务器中工作的自动设置。
  • 在描述设置时,我们总是首先考虑自动化,我们希望自动化将成为创建您自己的基础设施即代码的基础。
  • 所有命令均以用户身份运行 ,因为他们更改了基本系统设置,但直接以普通用户身份运行 WordPress。

设置环境变量

运行脚本之前设置以下环境变量:

  • WORDPRESS_DB_PASSWORD - WordPress数据库密码
  • WORDPRESS_ADMIN_USER - WordPress 管理员名称
  • WORDPRESS_ADMIN_PASSWORD - WordPress 管理员密码
  • WORDPRESS_ADMIN_EMAIL - WordPress 管理员电子邮件
  • WORDPRESS_URL 是 WordPress 网站的完整 URL,从 https://.
  • LETS_ENCRYPT_STAGING - 默认为空,但通过将该值设置为 1,您将使用 Let's Encrypt 临时服务器,这对于测试您的设置时频繁请求证书是必需的,否则 Let's Encrypt 可能会因大量请求而暂时阻止您的 IP 地址。

该脚本会检查这些与 WordPress 相关的变量是否已设置,如果没有则退出。
脚本第 572-576 行检查值 LETS_ENCRYPT_STAGING.

设置派生环境变量

第 55-61 行的脚本将以下环境变量设置为某个硬编码值或使用从上一节中设置的变量获得的值:

  • DEBIAN_FRONTEND="noninteractive" - 告诉应用程序它们正在脚本中运行并且不可能进行用户交互。
  • WORDPRESS_CLI_VERSION="2.4.0" 是 WordPress CLI 应用程序的版本。
  • WORDPRESS_CLI_MD5= "dedd5a662b80cda66e9e25d44c23b25c" — WordPress CLI 2.4.0 可执行文件的校验和(版本在变量中指定) WORDPRESS_CLI_VERSION)。 第 162 行的脚本使用此值来检查是否已下载正确的 WordPress CLI 文件。
  • UPLOAD_MAX_FILESIZE="16M" - WordPress 中可以上传的最大文件大小。 此设置会在多个地方使用,因此在一个地方设置它会更容易。
  • TLS_HOSTNAME= "$(echo ${WORDPRESS_URL} | cut -d'/' -f3)" - 系统的主机名,从 WORDPRESS_URL 变量检索。 用于从 Let's Encrypt 获取适当的 TLS/SSL 证书以及内部 WordPress 验证。
  • NGINX_CONF_DIR="/etc/nginx" - NGINX 设置的目录路径,包括主文件 nginx.conf.
  • CERT_DIR="/etc/letsencrypt/live/${TLS_HOSTNAME}" — WordPress 站点的 Let's Encrypt 证书的路径,从变量获取 TLS_HOSTNAME.

为 WordPress 服务器分配主机名

该脚本设置服务器的主机名以匹配站点的域名。 这不是必需的,但在设置单个服务器时,根据脚本的配置,通过 SMTP 发送外发邮件会更方便。

脚本代码

# Change the hostname to be the same as the WordPress hostname
if [ ! "$(hostname)" == "${TLS_HOSTNAME}" ]; then
  echo " Changing hostname to ${TLS_HOSTNAME}"
  hostnamectl set-hostname "${TLS_HOSTNAME}"
fi

将主机名添加到 /etc/hosts

增加 WP-Cron 用于运行定期任务,要求 WordPress 能够通过 HTTP 访问自身。 为了确保 WP-Cron 在所有环境下都能正常工作,脚本在文件中添加了一行 / etc / hosts文件这样WordPress就可以通过loopback接口访问自身:

脚本代码

# Add the hostname to /etc/hosts
if [ "$(grep -m1 "${TLS_HOSTNAME}" /etc/hosts)" = "" ]; then
  echo " Adding hostname ${TLS_HOSTNAME} to /etc/hosts so that WordPress can ping itself"
  printf "::1 %sn127.0.0.1 %sn" "${TLS_HOSTNAME}" "${TLS_HOSTNAME}" >> /etc/hosts
fi

安装后续步骤所需的工具

脚本的其余部分需要一些程序并假设存储库是最新的。 我们更新存储库列表,然后安装必要的工具:

脚本代码

# Make sure tools needed for install are present
echo " Installing prerequisite tools"
apt-get -qq update
apt-get -qq install -y 
  bc 
  ca-certificates 
  coreutils 
  curl 
  gnupg2 
  lsb-release

添加 NGINX 单元和 NGINX 存储库

该脚本从官方 NGINX 存储库安装 NGINX Unit 和开源 NGINX,以确保使用带有最新安全补丁和错误修复的版本。

该脚本添加 NGINX Unit 存储库,然后添加 NGINX 存储库,添加存储库密钥和配置文件 apt,定义通过 Internet 对存储库的访问。

NGINX Unit 和 NGINX 的实际安装将在下一节中进行。 我们预先添加存储库,因此不必多次更新元数据,这使得安装速度更快。

脚本代码

# Install the NGINX Unit repository
if [ ! -f /etc/apt/sources.list.d/unit.list ]; then
  echo " Installing NGINX Unit repository"
  curl -fsSL https://nginx.org/keys/nginx_signing.key | apt-key add -
  echo "deb https://packages.nginx.org/unit/ubuntu/ $(lsb_release -cs) unit" > /etc/apt/sources.list.d/unit.list
fi

# Install the NGINX repository
if [ ! -f /etc/apt/sources.list.d/nginx.list ]; then
  echo " Installing NGINX repository"
  curl -fsSL https://nginx.org/keys/nginx_signing.key | apt-key add -
  echo "deb https://nginx.org/packages/mainline/ubuntu $(lsb_release -cs) nginx" > /etc/apt/sources.list.d/nginx.list
fi

安装 NGINX、NGINX Unit、PHP MariaDB、Certbot (Let's Encrypt) 及其依赖项

添加所有存储库后,更新元数据并安装应用程序。 脚本安装的软件包还包括运行 WordPress.org 时推荐的 PHP 扩展

脚本代码

echo " Updating repository metadata"
apt-get -qq update

# Install PHP with dependencies and NGINX Unit
echo " Installing PHP, NGINX Unit, NGINX, Certbot, and MariaDB"
apt-get -qq install -y --no-install-recommends 
  certbot 
  python3-certbot-nginx 
  php-cli 
  php-common 
  php-bcmath 
  php-curl 
  php-gd 
  php-imagick 
  php-mbstring 
  php-mysql 
  php-opcache 
  php-xml 
  php-zip 
  ghostscript 
  nginx 
  unit 
  unit-php 
  mariadb-server

设置 PHP 以与 NGINX Unit 和 WordPress 一起使用

该脚本在目录中创建一个设置文件 确认。 这设置了 PHP 上传的最大大小,打开 PHP 错误输出到 STDERR,以便将它们写入 NGINX 单元日志,并重新启动 NGINX 单元。

脚本代码

# Find the major and minor PHP version so that we can write to its conf.d directory
PHP_MAJOR_MINOR_VERSION="$(php -v | head -n1 | cut -d' ' -f2 | cut -d'.' -f1,2)"

if [ ! -f "/etc/php/${PHP_MAJOR_MINOR_VERSION}/embed/conf.d/30-wordpress-overrides.ini" ]; then
  echo " Configuring PHP for use with NGINX Unit and WordPress"
  # Add PHP configuration overrides
  cat > "/etc/php/${PHP_MAJOR_MINOR_VERSION}/embed/conf.d/30-wordpress-overrides.ini" << EOM
; Set a larger maximum upload size so that WordPress can handle
; bigger media files.
upload_max_filesize=${UPLOAD_MAX_FILESIZE}
post_max_size=${UPLOAD_MAX_FILESIZE}
; Write error log to STDERR so that error messages show up in the NGINX Unit log
error_log=/dev/stderr
EOM
fi

# Restart NGINX Unit because we have reconfigured PHP
echo " Restarting NGINX Unit"
service unit restart

指定 WordPress 的 MariaDB 数据库设置

我们选择 MariaDB 而不是 MySQL,因为它有更多的社区活动,并且也可能 默认情况下提供更好的性能 (也许,这里一切都更简单:要安装 MySQL,您需要添加另一个存储库,大约。 译者)。

该脚本创建一个新的数据库并创建通过环回接口访问 WordPress 的凭据:

脚本代码

# Set up the WordPress database
echo " Configuring MariaDB for WordPress"
mysqladmin create wordpress || echo "Ignoring above error because database may already exist"
mysql -e "GRANT ALL PRIVILEGES ON wordpress.* TO "wordpress"@"localhost" IDENTIFIED BY "$WORDPRESS_DB_PASSWORD"; FLUSH PRIVILEGES;"

安装 WordPress CLI 程序

这一步,脚本安装程序 WP-CLI。 有了它,您可以安装和管理 WordPress 设置,而无需手动编辑文件、更新数据库或进入控制面板。 它还可用于安装主题和附加组件以及更新 WordPress。

脚本代码

if [ ! -f /usr/local/bin/wp ]; then
  # Install the WordPress CLI
  echo " Installing the WordPress CLI tool"
  curl --retry 6 -Ls "https://github.com/wp-cli/wp-cli/releases/download/v${WORDPRESS_CLI_VERSION}/wp-cli-${WORDPRESS_CLI_VERSION}.phar" > /usr/local/bin/wp
  echo "$WORDPRESS_CLI_MD5 /usr/local/bin/wp" | md5sum -c -
  chmod +x /usr/local/bin/wp
fi

安装和配置 WordPress

该脚本在目录中安装最新版本的 WordPress /var/www/wordpress并且还更改设置:

  • 数据库连接通过 unix 域套接字工作,而不是环回上的 TCP,以减少 TCP 流量。
  • WordPress 添加前缀 https:// 如果客户端通过 HTTPS 连接到 NGINX,则发送到 URL,并将远程主机名(由 NGINX 提供)发送到 PHP。 我们使用一段代码来设置它。
  • WordPress 需要 HTTPS 才能登录
  • 默认 URL 结构基于资源
  • 在文件系统上为 WordPress 目录设置正确的权限。

脚本代码

if [ ! -d /var/www/wordpress ]; then
  # Create WordPress directories
  mkdir -p /var/www/wordpress
  chown -R www-data:www-data /var/www

  # Download WordPress using the WordPress CLI
  echo " Installing WordPress"
  su -s /bin/sh -c 'wp --path=/var/www/wordpress core download' www-data

  WP_CONFIG_CREATE_CMD="wp --path=/var/www/wordpress config create --extra-php --dbname=wordpress --dbuser=wordpress --dbhost="localhost:/var/run/mysqld/mysqld.sock" --dbpass="${WORDPRESS_DB_PASSWORD}""

  # This snippet is injected into the wp-config.php file when it is created;
  # it informs WordPress that we are behind a reverse proxy and as such
  # allows it to generate links using HTTPS
  cat > /tmp/wp_forwarded_for.php << 'EOM'
/* Turn HTTPS 'on' if HTTP_X_FORWARDED_PROTO matches 'https' */
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) {
    $_SERVER['HTTPS'] = 'on';
}
if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
    $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
}
EOM

  # Create WordPress configuration
  su -s /bin/sh -p -c "cat /tmp/wp_forwarded_for.php | ${WP_CONFIG_CREATE_CMD}" www-data
  rm /tmp/wp_forwarded_for.php
  su -s /bin/sh -p -c "wp --path=/var/www/wordpress config set 'FORCE_SSL_ADMIN' 'true'" www-data

  # Install WordPress
  WP_SITE_INSTALL_CMD="wp --path=/var/www/wordpress core install --url="${WORDPRESS_URL}" --title="${WORDPRESS_SITE_TITLE}" --admin_user="${WORDPRESS_ADMIN_USER}" --admin_password="${WORDPRESS_ADMIN_PASSWORD}" --admin_email="${WORDPRESS_ADMIN_EMAIL}" --skip-email"
  su -s /bin/sh -p -c "${WP_SITE_INSTALL_CMD}" www-data

  # Set permalink structure to a sensible default that isn't in the UI
  su -s /bin/sh -p -c "wp --path=/var/www/wordpress option update permalink_structure '/%year%/%monthnum%/%postname%/'" www-data

  # Remove sample file because it is cruft and could be a security problem
  rm /var/www/wordpress/wp-config-sample.php

  # Ensure that WordPress permissions are correct
  find /var/www/wordpress -type d -exec chmod g+s {} ;
  chmod g+w /var/www/wordpress/wp-content
  chmod -R g+w /var/www/wordpress/wp-content/themes
  chmod -R g+w /var/www/wordpress/wp-content/plugins
fi

设置 NGINX 单元

该脚本配置 NGINX 单元来运行 PHP 并处理 WordPress 路径,隔离 PHP 进程命名空间并优化性能设置。 这里需要注意三个功能:

  • 对命名空间的支持由条件确定,基于检查脚本是否在容器中运行。 这是必要的,因为大多数容器设置不支持容器的嵌套启动。
  • 如果支持命名空间,请禁用该命名空间 网络。 这是为了允许 WordPress 连接到两个端点并同时在网络上可用。
  • 最大进程数定义如下: (运行 MariaDB 和 NGINX Uniy 的可用内存)/(PHP 中的 RAM 限制 + 5)
    该值在 NGINX 单元设置中设置。

该值还意味着始终至少有两个 PHP 进程在运行,这很重要,因为 WordPress 会向自身发出大量异步请求,并且如果没有额外的进程,运行例如 WP-Cron 将中断。 您可能需要根据本地设置增加或减少这些限制,因为此处创建的设置是保守的。 在大多数生产系统上,设置在 10 到 100 之间。

脚本代码

if [ "${container:-unknown}" != "lxc" ] && [ "$(grep -m1 -a container=lxc /proc/1/environ | tr -d '')" == "" ]; then
  NAMESPACES='"namespaces": {
        "cgroup": true,
        "credential": true,
        "mount": true,
        "network": false,
        "pid": true,
        "uname": true
    }'
else
  NAMESPACES='"namespaces": {}'
fi

PHP_MEM_LIMIT="$(grep 'memory_limit' /etc/php/7.4/embed/php.ini | tr -d ' ' | cut -f2 -d= | numfmt --from=iec)"
AVAIL_MEM="$(grep MemAvailable /proc/meminfo | tr -d ' kB' | cut -f2 -d: | numfmt --from-unit=K)"
MAX_PHP_PROCESSES="$(echo "${AVAIL_MEM}/${PHP_MEM_LIMIT}+5" | bc)"
echo " Calculated the maximum number of PHP processes as ${MAX_PHP_PROCESSES}. You may want to tune this value due to variations in your configuration. It is not unusual to see values between 10-100 in production configurations."

echo " Configuring NGINX Unit to use PHP and WordPress"
cat > /tmp/wordpress.json << EOM
{
  "settings": {
    "http": {
      "header_read_timeout": 30,
      "body_read_timeout": 30,
      "send_timeout": 30,
      "idle_timeout": 180,
      "max_body_size": $(numfmt --from=iec ${UPLOAD_MAX_FILESIZE})
    }
  },
  "listeners": {
    "127.0.0.1:8080": {
      "pass": "routes/wordpress"
    }
  },
  "routes": {
    "wordpress": [
      {
        "match": {
          "uri": [
            "*.php",
            "*.php/*",
            "/wp-admin/"
          ]
        },
        "action": {
          "pass": "applications/wordpress/direct"
        }
      },
      {
        "action": {
          "share": "/var/www/wordpress",
          "fallback": {
            "pass": "applications/wordpress/index"
          }
        }
      }
    ]
  },
  "applications": {
    "wordpress": {
      "type": "php",
      "user": "www-data",
      "group": "www-data",
      "processes": {
        "max": ${MAX_PHP_PROCESSES},
        "spare": 1
      },
      "isolation": {
        ${NAMESPACES}
      },
      "targets": {
        "direct": {
          "root": "/var/www/wordpress/"
        },
        "index": {
          "root": "/var/www/wordpress/",
          "script": "index.php"
        }
      }
    }
  }
}
EOM

curl -X PUT --data-binary @/tmp/wordpress.json --unix-socket /run/control.unit.sock http://localhost/config

设置 NGINX

配置基本 NGINX 设置

该脚本为 NGINX 缓存创建一个目录,然后创建主配置文件 nginx.conf。 注意handler进程的数量以及上传最大文件大小的设置。 还有一行包含下一节中定义的压缩设置文件,后面是缓存设置。

脚本代码

# Make directory for NGINX cache
mkdir -p /var/cache/nginx/proxy

echo " Configuring NGINX"
cat > ${NGINX_CONF_DIR}/nginx.conf << EOM
user nginx;
worker_processes auto;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       ${NGINX_CONF_DIR}/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    client_max_body_size ${UPLOAD_MAX_FILESIZE};
    keepalive_timeout  65;
    # gzip settings
    include ${NGINX_CONF_DIR}/gzip_compression.conf;
    # Cache settings
    proxy_cache_path /var/cache/nginx/proxy
        levels=1:2
        keys_zone=wp_cache:10m
        max_size=10g
        inactive=60m
        use_temp_path=off;
    include ${NGINX_CONF_DIR}/conf.d/*.conf;
}
EOM

设置 NGINX 压缩

在将内容发送到客户端之前对其进行动态压缩是提高站点性能的好方法,但前提是压缩配置正确。 这部分脚本基于设置 .

脚本代码

cat > ${NGINX_CONF_DIR}/gzip_compression.conf << 'EOM'
# Credit: https://github.com/h5bp/server-configs-nginx/
# ----------------------------------------------------------------------
# | Compression                                                        |
# ----------------------------------------------------------------------
# https://nginx.org/en/docs/http/ngx_http_gzip_module.html
# Enable gzip compression.
# Default: off
gzip on;
# Compression level (1-9).
# 5 is a perfect compromise between size and CPU usage, offering about 75%
# reduction for most ASCII files (almost identical to level 9).
# Default: 1
gzip_comp_level 6;
# Don't compress anything that's already small and unlikely to shrink much if at
# all (the default is 20 bytes, which is bad as that usually leads to larger
# files after gzipping).
# Default: 20
gzip_min_length 256;
# Compress data even for clients that are connecting to us via proxies,
# identified by the "Via" header (required for CloudFront).
# Default: off
gzip_proxied any;
# Tell proxies to cache both the gzipped and regular version of a resource
# whenever the client's Accept-Encoding capabilities header varies;
# Avoids the issue where a non-gzip capable client (which is extremely rare
# today) would display gibberish if their proxy gave them the gzipped version.
# Default: off
gzip_vary on;
# Compress all output labeled with one of the following MIME-types.
# `text/html` is always compressed by gzip module.
# Default: text/html
gzip_types
  application/atom+xml
  application/geo+json
  application/javascript
  application/x-javascript
  application/json
  application/ld+json
  application/manifest+json
  application/rdf+xml
  application/rss+xml
  application/vnd.ms-fontobject
  application/wasm
  application/x-web-app-manifest+json
  application/xhtml+xml
  application/xml
  font/eot
  font/otf
  font/ttf
  image/bmp
  image/svg+xml
  text/cache-manifest
  text/calendar
  text/css
  text/javascript
  text/markdown
  text/plain
  text/xml
  text/vcard
  text/vnd.rim.location.xloc
  text/vtt
  text/x-component
  text/x-cross-domain-policy;
EOM

为 WordPress 设置 NGINX

接下来,该脚本为 WordPress 创建一个配置文件 默认配置文件 在目录中 确认。 它在这里配置:

  • 激活通过 Certbot 从 Let's Encrypt 收到的 TLS 证书(设置将在下一节中进行)
  • 根据 Let's Encrypt 的建议配置 TLS 安全设置
  • 默认启用缓存跳过请求 1 小时
  • 对于两个常见请求的文件:favicon.ico 和 robots.txt,禁用访问日志记录以及未找到文件时的错误日志记录
  • 防止访问隐藏文件和某些文件 。PHP防止非法访问或意外启动
  • 禁用静态文件和字体文件的访问日志记录
  • 标题设置 访问控制允许来源 对于字体文件
  • 添加index.php 和其他静态信息的路由。

脚本代码

cat > ${NGINX_CONF_DIR}/conf.d/default.conf << EOM
upstream unit_php_upstream {
    server 127.0.0.1:8080;
    keepalive 32;
}
server {
    listen 80;
    listen [::]:80;
    # ACME-challenge used by Certbot for Let's Encrypt
    location ^~ /.well-known/acme-challenge/ {
      root /var/www/certbot;
    }
    location / {
      return 301 https://${TLS_HOSTNAME}$request_uri;
    }
}
server {
    listen      443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${TLS_HOSTNAME};
    root        /var/www/wordpress/;
    # Let's Encrypt configuration
    ssl_certificate         ${CERT_DIR}/fullchain.pem;
    ssl_certificate_key     ${CERT_DIR}/privkey.pem;
    ssl_trusted_certificate ${CERT_DIR}/chain.pem;
    include ${NGINX_CONF_DIR}/options-ssl-nginx.conf;
    ssl_dhparam ${NGINX_CONF_DIR}/ssl-dhparams.pem;
    # OCSP stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    # Proxy caching
    proxy_cache wp_cache;
    proxy_cache_valid 200 302 1h;
    proxy_cache_valid 404 1m;
    proxy_cache_revalidate on;
    proxy_cache_background_update on;
    proxy_cache_lock on;
    proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }
    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Deny all attempts to access hidden files such as .htaccess, .htpasswd,
    # .DS_Store (Mac)
    # Keep logging the requests to parse later (or to pass to firewall utilities
    # such as fail2ban)
    location ~ /. {
        deny all;
    }
    # Deny access to any files with a .php extension in the uploads directory;
    # works in subdirectory installs and also in multi-site network.
    # Keep logging the requests to parse later (or to pass to firewall utilities
    # such as fail2ban).
    location ~* /(?:uploads|files)/.*.php$ {
        deny all;
    }
    # WordPress: deny access to wp-content, wp-includes PHP files
    location ~* ^/(?:wp-content|wp-includes)/.*.php$ {
        deny all;
    }
    # Deny public access to wp-config.php
    location ~* wp-config.php {
        deny all;
    }
    # Do not log access for static assets, media
    location ~* .(?:css(.map)?|js(.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
        access_log off;
    }
    location ~* .(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
        add_header Access-Control-Allow-Origin "*";
        access_log off;
    }
    location / {
        try_files $uri @index_php;
    }
    location @index_php {
        proxy_socket_keepalive on;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $host;
        proxy_pass       http://unit_php_upstream;
    }
    location ~* .php$ {
        proxy_socket_keepalive on;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $host;
        try_files        $uri =404;
        proxy_pass       http://unit_php_upstream;
    }
}
EOM

为 Let's Encrypt 的证书设置 Certbot 并自动更新它们

Certbot 是来自电子前沿基金会 (EFF) 的免费工具,可让您从 Let's Encrypt 获取并自动续订 TLS 证书。 该脚本执行以下操作来配置 Certbot 以在 NGINX 中处理来自 Let's Encrypt 的证书:

  • 停止 NGINX
  • 下载推荐的 TLS 设置
  • 运行 Certbot 以获取站点的证书
  • 重新启动 NGINX 以使用证书
  • 将 Certbot 配置为每天凌晨 3:24 运行以检查证书是否需要续订,如有必要,下载新证书并重新启动 NGINX。

脚本代码

echo " Stopping NGINX in order to set up Let's Encrypt"
service nginx stop

mkdir -p /var/www/certbot
chown www-data:www-data /var/www/certbot
chmod g+s /var/www/certbot

if [ ! -f ${NGINX_CONF_DIR}/options-ssl-nginx.conf ]; then
  echo " Downloading recommended TLS parameters"
  curl --retry 6 -Ls -z "Tue, 14 Apr 2020 16:36:07 GMT" 
    -o "${NGINX_CONF_DIR}/options-ssl-nginx.conf" 
    "https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf" 
    || echo "Couldn't download latest options-ssl-nginx.conf"
fi

if [ ! -f ${NGINX_CONF_DIR}/ssl-dhparams.pem ]; then
  echo " Downloading recommended TLS DH parameters"
  curl --retry 6 -Ls -z "Tue, 14 Apr 2020 16:49:18 GMT" 
    -o "${NGINX_CONF_DIR}/ssl-dhparams.pem" 
    "https://raw.githubusercontent.com/certbot/certbot/master/certbot/certbot/ssl-dhparams.pem" 
    || echo "Couldn't download latest ssl-dhparams.pem"
fi

# If tls_certs_init.sh hasn't been run before, remove the self-signed certs
if [ ! -d "/etc/letsencrypt/accounts" ]; then
  echo " Removing self-signed certificates"
  rm -rf "${CERT_DIR}"
fi

if [ "" = "${LETS_ENCRYPT_STAGING:-}" ] || [ "0" = "${LETS_ENCRYPT_STAGING}" ]; then
  CERTBOT_STAGING_FLAG=""
else
  CERTBOT_STAGING_FLAG="--staging"
fi

if [ ! -f "${CERT_DIR}/fullchain.pem" ]; then
  echo " Generating certificates with Let's Encrypt"
  certbot certonly --standalone 
         -m "${WORDPRESS_ADMIN_EMAIL}" 
         ${CERTBOT_STAGING_FLAG} 
         --agree-tos --force-renewal --non-interactive 
         -d "${TLS_HOSTNAME}"
fi

echo " Starting NGINX in order to use new configuration"
service nginx start

# Write crontab for periodic Let's Encrypt cert renewal
if [ "$(crontab -l | grep -m1 'certbot renew')" == "" ]; then
  echo " Adding certbot to crontab for automatic Let's Encrypt renewal"
  (crontab -l 2>/dev/null; echo "24 3 * * * certbot renew --nginx --post-hook 'service nginx reload'") | crontab -
fi

对您的网站进行额外的定制

我们上面讨论了我们的脚本如何配置 NGINX 和 NGINX Unit 来为启用了 TLSSSL 的生产就绪站点提供服务。 您还可以根据您的需要,在将来添加:

为了获得更好的网站性能,我们建议升级到 NGINX Plus,我们基于开源 NGINX 的商业企业级产品。 其订阅者将收到动态加载的 Brotli 模块,以及(需额外付费) NGINX ModSecurity WAF。 我们还提供 NGINX 应用程序保护,基于 F5 业界领先的安全技术的 NGINX Plus 的 WAF 模块。

注: 如需支持高负载站点,您可以联系专家 南桥。 我们将确保您的网站或服务在任何负载下快速可靠地运行。

来源: habr.com