Configuración de WordPress con NGINX
He estado instalando algunos sitios WordPress en mi nuevo VPS con NGINX.
Instalar WordPress con Nginx no es tan complicado como parece, pero hay que hacer algunas configuraciones para aumentar la seguridad y para que funcione con los plugins de caché.
Como plugin de caché he elegido W3 Total Cache porque el método «Page Cache», «disk:enhanced» permite servir páginas HTML estáticas de mi sitio e incluye otras mejoras de rendimiento.
No voy a explicar todo el proceso de instalar y configurar NGINX. Aquí encontrarás algunos tutoriales si buscas eso.
Lo primero es incluir la configuración de tu dominio/servidor en «/etc/nginx/sites-available». Crea un archivo nuevo con este contenido y adáptalo a tu dominio y tus rutas:
1server {
2 listen 80; ## listen for ipv4
3 listen [::]:80; ## listen for ipv6
4 server_name domain.com;
5 access_log /var/log/nginx/domain.com.access.log;
6 error_log /var/log/nginx/domain.com.error.log;
7
8 root /folder/with/wordpress/installation/;
9
10 # Include wordpress config file
11 include sites-available/wordpress.conf;
12}Como tengo varias instalaciones de WordPress en mi servidor, voy a separar la configuración de WordPress en otro archivo y usarlo en mis distintas configuraciones de servidor. He creado un archivo nuevo llamado «wordpress.conf» en «/etc/nginx/sites-available» (el archivo está comentado para explicar las distintas opciones)
1index index.php index.html;
2
3set $cache_uri $request_uri;
4
5# POST requests and urls with a query string should always go to PHP
6if ($request_method = POST) {
7 set $cache_uri 'null cache';
8}
9if ($query_string != "") {
10 set $cache_uri 'null cache';
11}
12# Don't use the cache for logged in users or recent commenters
13if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
14 set $cache_uri 'null cache';
15}
16
17# Use cached or actual file if they exists, otherwise pass request to WordPress
18location / {
19 rewrite ^([^.]*[^/])$ $1/ permanent;
20 try_files /wp-content/cache/page_enhanced/${host}${cache_uri}_index.html $uri $uri/ /index.php?$args;
21}
22
23location ~ ^/wp-content/cache/minify/[^/]+/(.*)$ {
24 try_files $uri /wp-content/plugins/w3-total-cache/pub/minify.php?file=$1;
25}
26
27# Show "Not Found" 404 errors in place of "Forbidden" 403 errors, because
28# forbidden errors allow attackers potential insight into your server's
29# layout and contents
30 error_page 403 =404;
31
32# Prevent access to any files starting with a dot, like .htaccess
33# or text editor temp files
34 location ~ /\. { access_log off; log_not_found off; deny all; }
35
36# Prevent access to any files starting with a $ (usually temp files)
37 location ~ ~$ { access_log off; log_not_found off; deny all; }
38
39# Do not log access to robots.txt, to keep the logs cleaner
40 location = /robots.txt { access_log off; log_not_found off; }
41
42# Do not log access to the favicon, to keep the logs cleaner
43 location = /favicon.ico { access_log off; log_not_found off; }
44
45# Keep images, CSS and other static files around in browser cache for
46# as long as possible, to cut down on server load
47location ~* .(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
48 expires max; log_not_found off; access_log off;
49}
50
51# Common deny or internal locations, to help prevent access to areas of
52# the site that should not be public
53 location ~* wp-admin/includes { deny all; }
54 location ~* wp-includes/theme-compat/ { deny all; }
55 location ~* wp-includes/js/tinymce/langs/.*\.php { deny all; }
56 location /wp-content/ { internal; }
57 location /wp-includes/ { internal; }
58# Protects the wp-config.php|readme.html|license.txt files from being
59# accessed (uncomment after wordpress installation)
60# location ~ /(\.|wp-config.php|readme.html|license.txt) { deny all; }
61
62# Prevent any potentially-executable files in the uploads directory from
63# being executed by forcing their MIME type to text/plain
64 location ~* ^/wp-content/uploads/.*.(html|htm|shtml|php)$ {
65 types { }
66 default_type text/plain;
67 }
68
69# Add trailing slash to */wp-admin requests so the admin interface
70# works correctly
71 rewrite /wp-admin$ $scheme://$host$uri/ permanent;
72
73location ~ \.php$ {
74 fastcgi_pass 127.0.0.1:9000;
75 fastcgi_index index.php;
76 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
77 include fastcgi_params;
78}Ahora tienes que crear un enlace simbólico del primer archivo que has creado en «/etc/nginx/sites-enabled» y reiniciar nginx.
Después puedes instalar WordPress con normalidad. Una vez instalado, conviene descomentar la línea 59 del archivo «wordpress.conf» ( location ~ /(.|wp-config.php|readme.html|license.txt) { deny all; } ) para impedir el acceso al archivo config.php, al readme y a la licencia.
Para el plugin W3 Total Cache, puedes activar la caché de páginas como «disk:enhanced» para servir las páginas cacheadas de tu sitio. También puedes activar la minificación o cualquier otra opción (Object and Database Cache, CDN … etc.). La «Browser cache» no es realmente necesaria porque NGINX se encarga de ella.
Y eso es todo 🙂 Cualquier comentario o mejora se agradece.
Fuentes: