WordPress Nginx 配置指南

这篇文章大部分来自对wordpress.org官网的翻译。满意之后会提交给官方。
https://codex.wordpress.org/Nginx

LAMP(Linux + Apache + MySQL + PHP)现在是建立WordPress最流行的技术栈,但也可以使用Nginx。WordPress支持Nginx,类似WordPress.com的大型WordPress网站,就是基于Nginx的。

有很多方法实施Nginx。可以做为Aach的前置reverse-proxy(反向代理),可以同时使用Apache的特性、功能,又获得Nginx高速的优点。很多使用nginx的网站实际上都是运行着Apache,Nginx做为reverse proxy。

这篇指南主要用于独立的Nginx setup配置,Nginx代替Apache做为主服务器。请注意,Nginx并不是Apache的完全替代品。关于WordPress的部署启动,动手之前请注意这些关键点:

  • Nginx没有目录级配置文件(类似Apache的.htaccess 或IIS的web.config文件)。所有的配置都在管理员处理server level时完成,所有WordPress无法修正配置。
  • 当使用Nginx的时候,仿固定链接功能(Pretty Permalinks functionality)有些不同
  • 因为Nginx没有.htaccess-type 能力,所以WordPress无法为你自动修正服务器配置。(不能自动产生rewrite rules)
  • 如果你没有修改install, "index.php"将被添加到你的固定链接。(通过插件或者在子主题"child theme"的functions.php中添加自定义代码)
  • 最后,如果你一定要使用一些.htaccess 的某些功能,技术上来说,可以通过安装htscanner PECL extension for PHP实现。 (请注意,这不是一个完美的解决方案,所以在网站上线使用之前,请对其进行充分的测试和Debug)

这篇指南并不包括安装和配置Nginx,建议你已经安装了Nginx,并了解Nginx的基本工作调试知识后再进行阅读。

通用多站点支持(Generic and Multi-Site Support)

WordPress要与Nginx一起工作,必须先配置后端php-cgi,可选择 FastCGI 或 PHP - FPM 。因为 PHP 5.3 中php-fpm已经直接安装,所以我们就用它了。

Nginx 配置已分成 5 个不同文件 , 为了便于理解,对每个设置都已经详细注释。笔者尽量尝试做 Nginx 配置的“最佳实践”。

主启动文件(通用)

此文件就是 /etc/nginx/nginx.conf (或者 /etc/nginx/conf/nginx.conf 如用的是 Arch Linux).

# Generic startup file.
user {user} {group};

#一般等于你的CPU数。执行命令 "grep processor /proc/cpuinfo | wc -l" 可获得
worker_processes  2;

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/*;
}

与标准的 nginx.conf 文件稍微有点不同,此配置遵循 Ubuntu / Debian 声明的最大弹性启动站点(enabled sites)法- - 用“sites-available”存储一个配置, 然后链接到"sites-enabled"中的配置文件 。

单站点配置(Per Site Configuration)

# Redirect everything to the main site. We use a separate server statement and NOT an if statement - see http://wiki.nginx.org/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;

    #附加规则可以写在这里

    # 下面的文件只能包含一个
    include global/wordpress.conf;
#   include global/wordpress-ms-subdir.conf;
#   include global/wordpress-ms-subdomain.conf;
}

将配置分成多个片段放在多个文件中,可以允许同样的逻辑复用。'global'子目录可用于添加额外功能配置(通用功能)。(基于Nginx的安装设置情况,目录可能是 /etc/nginx/conf/global/ 也可能是 /etc/nginx/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;
}

General WordPress rules

对于单个站点安装情况来说,这就是 '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;
                fastcgi_buffers 16 16k;
                fastcgi_buffer_size 32k;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }
}

nginxv.10及之后版本的最新例子,请Ref: https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/

WordPress Multisite Subdirectory rules

多网站子目录安装,对应的 'global/wordpress.conf'文件如下:

# WordPress multisite subdirectory rules.
# Designed to be included in any server {} block.
map $uri $blogname{
    ~^(?P/[^/]+/)files/(.*)       $blogpath ;
}

map $blogname $blogid{
    default -999;

    #Ref: http://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$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
}

Ref: https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/

HTTPS in Nginx

在Nginx中打开HTTPS非常简单(译者:确实简单,但是WordPress要跑正确可不容易,大家记得要保留http的入口,另外后台设置的地址记得修改)

server {
    # 同时监听 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 ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:CAMELLIA256-SHA:CAMELLIA128-SHA256;
}

Mozilla 提供了一个非常棒的 SSL 配置生成工具。

PS:下面是关于引用和缓存的一些东西。待续:

WP Super Cache Rules

W3Total Cache Rules

Nginx fastcgi_cache

Better Performance for Static Files in Multisite

Notes

你可能感兴趣的:(WordPress Nginx 配置指南)