虽然LAMP堆栈(Linux + Apache + MySQL + PHP)非常受欢迎,但也可以使用NGINX。WordPress支持NGINX,一些大型WordPress站点(例如WordPress.com)由NGINX提供动力。
在谈论NGINX时,重要的是要知道有多种实现NGINX的方法。它可以在Apache前面设置为逆转录,这是一个非常强大的设置,可让您使用Apache的所有功能和功能,同时从NGINX的速度中受益。大多数使用NGINX作为服务器报告的网站(基于从HTTP响应标头收集的统计数据)实际上是用Nginx作为反向代理运行的Apache。(反向proxy报告了显示“ nginx”的HTTP响应标头,而不是服务器本身。)
本指南是指独立的NGINX设置,在该设置中,它用作主服务器而不是Apache。 应该注意的是,Nginx不是完全可以互换的Apache替代品。在进行前进之前,您需要了解一些关键差异,然后需要注意:
- 使用nginx,没有目录级配置文件,例如apache的.htaccess或iis的web.config文件。所有配置都必须由管理员在服务器级别完成,并且WordPress无法像Apache或IIS一样修改配置。
- 运行NGINX时,漂亮的永久链接功能略有不同。
- 由于NGINX没有.htaccess-type功能,并且WordPress无法自动为您修改服务器配置,因此它无法为您生成重写规则。
- 如果不修改安装,“ index.php”将添加到永久链接中。(有多种方法可以通过插件来减轻此功能(请参见下文)和/或将自定义代码添加到您的子主题函数。
- 但是,如果您确实想拥有一些(有限).htaccess的功能,那么从技术上讲可以通过安装来添加 PHP的HTSCANNER PECL扩展。(但是,这不是一个完美的解决方案,因此请确保在使用实时网站之前对其进行彻底测试和调试。)
本指南不会涵盖如何安装和配置NGINX,因此假设您已经安装了NGINX,并且对如何使用和调试它有基本的了解。
通用和多站点支持
要使WordPress与NGINX一起使用,您必须配置后端PHP-CGI。可用的选项是fastcgi
或者php-fpm
。在这里,使用php-fpm是因为它包含在PHP 5.3+中,因此安装它是直接的。
NGINX配置已分解为五个不同的文件,并经过大量评论,以使每个选项更易于理解。这 作者 还使尝试遵循NGINX配置的“最佳实践”做出了最好的努力。
主(通用)启动文件
这相当于/etc/nginx/nginx.conf(OR/etc/nginx/conf/nginx.conf,如果您使用的是Arch Linux)。
# Generic startup file.
user {user} {group};
#usually equal to number of CPUs you have. run command "grep processor /proc/cpuinfo | wc -l" to find it
worker_processes auto;
worker_cpu_affinity auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
# Keeps the logs free of messages about not being able to bind().
#daemon off;
events {
worker_connections 1024;
}
http {
#rewrite_log on;
include mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
sendfile on;
#tcp_nopush on;
keepalive_timeout 3;
#tcp_nodelay on;
#gzip on;
#php max upload limit cannot be larger than this
client_max_body_size 13m;
index index.php index.html index.htm;
# Upstream to abstract backend connection(s) for PHP.
upstream php {
#this should match value of "listen" directive in php-fpm pool
server unix:/tmp/php-fpm.sock;
# server 127.0.0.1:9000;
}
include sites-enabled/*;
}
每个站点配置
# Redirect everything to the main site. We use a separate server statement and NOT an if statement - see https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/
server {
server_name _;
return 302 $scheme://example.com$request_uri;
}
server {
server_name example.com;
root /var/www/example.com;
index index.php;
include global/restrictions.conf;
# Additional rules go here.
# Only include one of the files below.
include global/wordpress.conf;
# include global/wordpress-ms-subdir.conf;
# include global/wordpress-ms-subdomain.conf;
}
将配置的部分分成多个文件可以一遍又一遍地重复使用相同的逻辑。“全局”子目录用于为通用使用添加额外的规则(/etc/nginx/conf/conf/conf/conf/conf/etc/etc/etc/nginx/global/global/global/global/global/global/global/global/global/global/global/global/global/global/global/global/global/global/global/
全局限制文件
# Global restrictions configuration file.
# Designed to be included in any server {} block.
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 sub-directory installs and also in multisite network
# Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
location ~* /(?:uploads|files)/.*\.php$ {
deny all;
}
一般WordPress规则
对于单个站点安装,这是global/wordpress.conf
文件:
# WordPress single site rules.
# Designed to be included in any server {} block.
# Upstream to abstract backend connection(s) for php
upstream php {
server unix:/tmp/php-cgi.socket;
server 127.0.0.1:9000;
}
server {
## Your website name goes here.
server_name domain.tld;
## Your only path reference.
root /var/www/wordpress;
## This should be in your http block and if it is, it's not needed here.
index index.php;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location / {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
#NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
include fastcgi.conf;
fastcgi_intercept_errors on;
fastcgi_pass php;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}
这是NGINX的最新示例:https://www.nginx.com/resources/wiki/wiki/start/topics/recipes/wordpress/
WordPress多站点
对于多站点安装,请使用以下部分之一global/wordpress.conf
文件,取决于多站点时使用的WordPress版本活性,以及域/子目录配置。
WordPress 3.5及以上
如果您在WordPress 3.5或更高版本上激活了多站点,请使用其中之一。
WordPress 3.5及以上的子目录示例
# WordPress multisite subdirectory config file for WP 3.5 and up.
server {
server_name example.com ;
root /var/www/example.com/htdocs;
index index.php;
if (!-e $request_filename) {
rewrite /wp-admin$ $scheme://$host$request_uri/ permanent;
rewrite ^(/[^/]+)?(/wp-.*) $2 last;
rewrite ^(/[^/]+)?(/.*\.php) $2 last;
}
location / {
try_files $uri $uri/ /index.php?$args ;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_pass php;
}
#add some rules for static content expiry-headers here
}
WordPress 3.5及以上的子域示例
# WordPress multisite subdomain config file for WP 3.5 and up.
server {
server_name example.com *.example.com ;
root /var/www/example.com/htdocs;
index index.php;
location / {
try_files $uri $uri/ /index.php?$args ;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_pass php;
}
#add some rules for static content expiry-headers here
}
WordPress 3.4及以下
如果您最初使用3.4或以上的WordPress激活多站点,则需要使用其中之一:
WordPress <= 3.4子目录示例
# WordPress multisite subdirectory config file for WP 3.4 and below.
map $uri $blogname{
~^(?P<blogpath>/[^/]+/)files/(.*) $blogpath ;
}
map $blogname $blogid{
default -999;
#Ref: https://wordpress.org/extend/plugins/nginx-helper/
#include /var/www/wordpress/wp-content/plugins/nginx-helper/map.conf ;
}
server {
server_name example.com ;
root /var/www/example.com/htdocs;
index index.php;
location ~ ^(/[^/]+/)?files/(.+) {
try_files /wp-content/blogs.dir/$blogid/files/$2 /wp-includes/ms-files.php?file=$2 ;
access_log off; log_not_found off; expires max;
}
#avoid php readfile()
location ^~ /blogs.dir {
internal;
alias /var/www/example.com/htdocs/wp-content/blogs.dir ;
access_log off; log_not_found off; expires max;
}
if (!-e $request_filename) {
rewrite /wp-admin$ $scheme://$host$request_uri/ permanent;
rewrite ^(/[^/]+)?(/wp-.*) $2 last;
rewrite ^(/[^/]+)?(/.*\.php) $2 last;
}
location / {
try_files $uri $uri/ /index.php?$args ;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_pass php;
}
#add some rules for static content expiry-headers here
}
NGINX提供了2个特殊指令:X-Accel-redirect和Map。使用这两个指令,可以消除在WordPress多站点网络上静态文件的性能命中。
WordPress <= 3.4子域示例
# WordPress multisite subdomain config file for WP 3.4 and below.
map $http_host $blogid {
default -999;
#Ref: https://wordpress.org/extend/plugins/nginx-helper/
#include /var/www/wordpress/wp-content/plugins/nginx-helper/map.conf ;
}
server {
server_name example.com *.example.com ;
root /var/www/example.com/htdocs;
index index.php;
location / {
try_files $uri $uri/ /index.php?$args ;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_pass php;
}
#WPMU Files
location ~ ^/files/(.*)$ {
try_files /wp-content/blogs.dir/$blogid/$uri /wp-includes/ms-files.php?file=$1 ;
access_log off; log_not_found off; expires max;
}
#WPMU x-sendfile to avoid php readfile()
location ^~ /blogs.dir {
internal;
alias /var/www/example.com/htdocs/wp-content/blogs.dir;
access_log off; log_not_found off; expires max;
}
#add some rules for static content expiry-headers here
}
参考:https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/
nginx中的https
在NGINX中启用HTTPS相对简单。
server {
# listens both on IPv4 and IPv6 on 443 and enables HTTPS and HTTP/2 support.
# HTTP/2 is available in nginx 1.9.5 and above.
listen *:443 ssl http2;
listen [::]:443 ssl http2;
# indicate locations of SSL key files.
ssl_certificate /srv/www/ssl/ssl.crt;
ssl_certificate_key /srv/www/ssl/ssl.key;
ssl_dhparam /srv/www/master/ssl/dhparam.pem;
# indicate the server name
server_name example.com *.example.com;
# Enable HSTS. This forces SSL on clients that respect it, most modern browsers. The includeSubDomains flag is optional.
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
# Set caches, protocols, and accepted ciphers. This config will merit an A+ SSL Labs score as of Sept 2015.
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5';
}
Mozilla提供 出色的SSL配置生成工具 也是如此。
WP超级缓存规则
# WP Super Cache rules.
# Designed to be included from a 'wordpress-ms-...' configuration file.
set $cache_uri $request_uri;
# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
set $cache_uri 'null cache';
}
if ($query_string != "") {
set $cache_uri 'null cache';
}
# Don't cache uris containing the following segments
if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
set $cache_uri 'null cache';
}
# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
set $cache_uri 'null cache';
}
# START MOBILE
# Mobile browsers section to server them non-cached version. COMMENTED by default as most modern wordpress themes including twenty-eleven are responsive. Uncomment config lines in this section if you want to use a plugin like WP-Touch
# if ($http_x_wap_profile) {
# set $cache_uri 'null cache';
#}
#if ($http_profile) {
# set $cache_uri 'null cache';
#}
#if ($http_user_agent ~* (2.0\ MMP|240x320|400X240|AvantGo|BlackBerry|Blazer|Cellphone|Danger|DoCoMo|Elaine/3.0|EudoraWeb|Googlebot-Mobile|hiptop|IEMobile|KYOCERA/WX310K|LG/U990|MIDP-2.|MMEF20|MOT-V|NetFront|Newt|Nintendo\ Wii|Nitro|Nokia|Opera\ Mini|Palm|PlayStation\ Portable|portalmmm|Proxinet|ProxiNet|SHARP-TQ-GX10|SHG-i900|Small|SonyEricsson|Symbian\ OS|SymbianOS|TS21i-10|UP.Browser|UP.Link|webOS|Windows\ CE|WinWAP|YahooSeeker/M1A1-R2D2|iPhone|iPod|Android|BlackBerry9530|LG-TU915\ Obigo|LGE\ VX|webOS|Nokia5800)) {
# set $cache_uri 'null cache';
#}
#if ($http_user_agent ~* (w3c\ |w3c-|acs-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-|dang|doco|eric|hipt|htc_|inno|ipaq|ipod|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-|lg/u|maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo|teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|wap-|wapa|wapi|wapp|wapr|webc|winw|winw|xda\ |xda-)) {
# set $cache_uri 'null cache';
#}
#END MOBILE
# Use cached or actual file if they exists, otherwise pass request to WordPress
location / {
try_files /wp-content/cache/supercache/$http_host/$cache_uri/index.html $uri $uri/ /index.php?$args ;
}
实验修改:
如果您使用的是HTTPS,则最新的WP Super Cache的开发版本可能会使用不同的目录结构来区分HTTP和HTTPS。try_files行可能看起来像以下内容:
location / {
try_files /wp-content/cache/supercache/$http_host/$cache_uri/index-https.html $uri $uri/ /index.php?$args ;
}
W3总缓存规则
W3总高速缓存使用不同的目录结构来基于磁盘的缓存存储,具体取决于WordPress配置。
缓存验证检查将保持常见,如下所示:
#W3 TOTAL CACHE CHECK
set $cache_uri $request_uri;
# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
set $cache_uri 'null cache';
}
if ($query_string != "") {
set $cache_uri 'null cache';
}
# Don't cache uris containing the following segments
if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
set $cache_uri 'null cache';
}
# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
set $cache_uri 'null cache';
}
#ADD mobile rules from WP SUPER CACHE section above
#APPEND A CODE BLOCK FROM BELOW...
对于普通的WordPress(无多站点)
使用以下:
# Use cached or actual file if they exists, otherwise pass request to WordPress
location / {
try_files /wp-content/w3tc/pgcache/$cache_uri/_index.html $uri $uri/ /index.php?$args ;
}
用于子目录的多站点
使用以下内容:
if ( $request_uri ~* "^/([_0-9a-zA-Z-]+)/.*" ){
set $blog $1;
}
set $blog "${blog}.";
if ( $blog = "blog." ){
set $blog "";
}
# Use cached or actual file if they exists, otherwise pass request to WordPress
location / {
try_files /wp-content/w3tc-$blog$host/pgcache$cache_uri/_index.html $uri $uri/ /index.php?$args ;
}
用于子域/域映射的多站点
使用以下:
location / {
try_files /wp-content/w3tc-$host/pgcache/$cache_uri/_index.html $uri $uri/ /index.php?$args;
}
笔记
- NGINX可以自动处理GZIP和浏览器缓存,因此最好将该部分留给Nginx。
- W3总CACHE MINIFY规则将与上述配置合作,而无需任何问题。
nginx fastcgi_cache
Nginx可以自行执行缓存,以减少服务器上的负载。当您想使用Nginx的内置fastcgi_cache时,最好与 fastcgi_cache_purge 模块。编辑后,它将帮助NGINX清除缓存。在WordPress侧,您需要安装一个插件 Nginx助手 利用fastcgi_cache_purge功能。
配置看起来如下:
在http {…}块中定义nginx缓存区域,外部服务器{…}块
#move next 3 lines to /etc/nginx/nginx.conf if you want to use fastcgi_cache across many sites
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:500m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
对于WordPress站点配置,在服务器{..}块中添加缓存检查块如下
#fastcgi_cache start
set $no_cache 0;
# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
set $no_cache 1;
}
if ($query_string != "") {
set $no_cache 1;
}
# Don't cache uris containing the following segments
if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
set $no_cache 1;
}
# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
set $no_cache 1;
}
然后更改PHP处理块
只需将其添加到以下PHP块中即可。注意fastcgi_cache_valid行200 60m;它仅告诉NGINX仅缓存200个响应(正常页面),这意味着重定向不会被缓存。这对于多语言站点很重要,如果未实施,则NGINX将以一种语言缓存主URL,而不是根据其语言将用户重定向到其各自的内容。
fastcgi_cache_bypass $no_cache;
fastcgi_no_cache $no_cache;
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 200 60m;
这样就变成了这样
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
return 404;
}
# This is a robust solution for path info security issue and works with "cgi.fix_pathinfo = 1" in /etc/php.ini (default)
include fastcgi.conf;
fastcgi_index index.php;
# fastcgi_intercept_errors on;
fastcgi_pass php;
fastcgi_cache_bypass $no_cache;
fastcgi_no_cache $no_cache;
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 200 60m;
}
最后添加一个有条件清除的位置
location ~ /purge(/.*) {
# Uncomment the following two lines to allow purge only from the webserver
# allow 127.0.0.1;
# deny all;
fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
}
如果您获得“未知指令”“ fastcgi_cache_purge”,则错误检查您的nginx安装是否具有fastcgi_cache_purge模块。
多站点中静态文件的性能更好(WP <= 3.4)
默认情况下,在3.5之前激活的多站点网络上,静态文件请求将PHP带入图片,即ms-files.php
文件。您可以使用nginx获得更好的性能Map{..}
指示。
在您网站的Nginx配置中server{..}
块,添加一个部分,如下所示:
map $http_host $blogid {
default 0;
example.com 1;
site1.example.com 2;
site1.com 2;
}
它只是站点名称和博客ID的列表。您可以使用 Nginx助手 获取这样的站点名称/Blog-ID对列表。该插件还将生成一个map.conf
您可以将其直接包含在map{}
这样的部分:
map $http_host $blogid {
default 0;
include /path/to/map.conf ;
}
创建一个map{..}
部分,您只需要对NGINX配置进行多个更改,以便首先使用Nginx处理 / files /的请求map{..}
:
location ~ ^/files/(.*)$ {
try_files /wp-content/blogs.dir/$blogid/$uri /wp-includes/ms-files.php?file=$1 ;
access_log off; log_not_found off; expires max;
}
笔记
- 每当创建新站点,删除或额外的域映射到现有站点时,Nginx助手将自动更新Map.conf文件,但您仍然需要手动重新加载Nginx配置。您以后可以随时这样做。直到那时,只能使用PHP-FPM提供新网站的文件。
- 此方法不会生成任何符号链接。因此,遵循符号链接的意外删除或备份脚本不会存在任何问题。
- 对于大型网络,这将很好地扩展,因为将会有一个Map.conf文件。
最后几个但重要的说明:整个设置都假定该网站的根源是博客,并且所有将引用的文件都位于主机上。如果将博客放在 /博客等子目录中,则必须修改规则。也许有人可以采取这些规则,并可以使用A:
set $wp_subdir "/blog";
主“服务器”块中的指令,并使其自动应用于通用WP规则。
警告
一个错字 全局限制文件 可以创建漏洞。要测试您的“上传”目录是否真的受到保护,请创建一个带有某些内容的PHP文件(示例:),将其上传到“上传”目录(或其一个子目录之一),然后尝试从您的浏览器。
资源
参考
外部链接
- nginx WordPress Wiki页面
- Linode图书馆的LEMP指南
- Linode库上有关NGINX的各种指南
- 使用PHP-FPM和NGINX的Lightning快速WordPress
- 虚拟主机示例
- 常见情况的20多个WordPress-nginx教程列表
- NGINX配置简介
- 关于使用nginx自己托管WordPress的全面博客系列
- WordPress安装Centminmod
- NGINX WordPress安装指南
脚本和工具
用于WordPress Nginx脚本安装 Centminmod 可用于Centos。
确保nginx
ChangElog
- 2022-10-25:原始内容 nginx。