S
SrMendez
Gamma
Programador
Creo que de todos los tutoriales que hay en la internet y no solo por allí afuera sino aquí este será el primero que ni siquiera en ningún tipo de comunidad es existente hasta este momento, y esto es debido a que nadie le gusta compartir un conocimiento tan poderoso como este como lo es formar una alternativa potente al LiteSpeed sin negativas en el performance. Antes de iniciar este tutorial cabe mencionar que realice varias pruebas no obstante tengo en funcionamiento esta estrategia bajo servidores de producción con más de 400 cuentas.
Como dice el titulo acá aprenderás a instalar Nginx sin ningún tipo de errores en WHM/cPanel (no importa si es cPanel con CentOS 6 o CentOS 7, funciona igual), con Varnish, Google PageSpeed, Memcached y Mod_Cloudflare para los que tienen problemas con el Proxy del mismo a continuación.
Puntos a tomar en cuenta:
1. Si, los problemas del GeoIP y/o de que el Varnish da el IP del servidor camuflando el IP del usuario, con este tutorial lo tienes totalmente resuelto :encouragement:
2. Nginx y Varnish forman una perfecta amistad, ahora todo depende de cómo lo configures tu en lo personal, yo solo te daré mis instrucciones básicas de como formar algo único.
3. Sé que muchos dirán que el Pagespeed no es tan bueno pero yo te digo a ti que esto es una bomba trabajando en función con los antes mencionados, Nginx y Varnish.
4. El Pagespeed que vas a instalar, lo vas a instalar con Nginx en cPanel y no con Apache puesto a que lo que vamos a estar usando como Proxy es el Nginx.
5. Si después de hacer al pie de la letra este manual, toma en cuenta que si usas Flexicache como plugin en WordPress, o como WP Minify Fix te puede traer inconvenientes, desactívalos. Lo que si puedes usar es WP Autoptimize, LazyLoad entre otros del montón.
6. Considero que todo tutorial parecido a este que aparezca en la internet luego de esta publicación/redacción, es una autentica copia de este único y hermoso manual.
Enciendan sus motores, y a correr!
Aviso: Una vez hecho todo esto toma en cuenta que debido a que el Nginx no está totalmente familiarizado con el EasyApache, posiblemente no podrás hacer un setup, y con setup me refiero a que no podrás ir a cambiar la versión del php o instalar cosas a través del mismo hasta no desinstalar Nginx primero para poder hacer tales cambios así que asegúrate de que si vas a instalar algo u actualizar algo a través del EasyApache este hecho antes de proceder con el manual. De todas formas más adelante te explico cómo desinstalarlo sin tocar los demás complementos.
P0: Instalar Mod_Cloudflare
Insertar CODE, HTML o PHP:
perl <(GET https://raw.github.com/tylerl/util/master/easyapache/cloudflare.pl) install
Si por alguna rara razón falla.
Insertar CODE, HTML o PHP:
wget https://raw.github.com/tylerl/util/master/easyapache/cloudflare.pl;perl cloudflare.pl install
Si le quieres poner Cloudflare al sitio web, y quieres saber la IP real de los visitantes esto resuelve el tema por completo, finalmente vas a ir al EasyApache, lo vas a seleccionar y vas hacerle un rebuild o setup, cuando este termine entonces procedes con lo siguiente a continuación.
P1: Instalar Memcached
Insertar CODE, HTML o PHP:
yum install epel-* epel-release* -y;yum install nano* memcached* libmemcached* -y
P2: Configurar Memcached
Insertar CODE, HTML o PHP:
chkconfig memcached on;service memcached restart;nano /etc/sysconfig/memcached
Ajústalas a tu manera, luego guárdalas con ctrl + o...
Insertar CODE, HTML o PHP:
PORT="11211"
USER="memcached"
MAXCONN="5000"
CACHESIZE="1000"
OPTIONS=""
Insertar CODE, HTML o PHP:
service memcached restart
P3: Instalar Nginx
Nota: El nginx provisto por los pésimos de Syslint.com es totalmente una basura y completa copia del gratuito, por lo mismo no es compatible con este manual.
1) - Arreglar los errores comunes
Insertar CODE, HTML o PHP:
cp /var/cpanel/templates/apache2_4/* /var/cpanel/templates/apache2
2) - Arreglar un problema común
Insertar CODE, HTML o PHP:
find ./ -type f -print0 | xargs -0 sed -i 's/listen \[::\]:80;/#listen \[::\]:80;/g'
3) - Que Nginx haga lo suyo
Insertar CODE, HTML o PHP:
cd /usr/local/src;wget http://nginxcp.com/latest/nginxadmin.tar;tar xf nginxadmin.tar;cd publicnginx;./nginxinstaller install
P4: Instalar PageSpeed
Insertar CODE, HTML o PHP:
cd /usr/local/src/publicnginx;wget https://github.com/pagespeed/ngx_pagespeed/archive/master.zip;yum install zip -y;unzip master.zip;cd ngx_pagespeed-master;wget https://dl.google.com/dl/page-speed/psol/1.9.32.6.tar.gz;tar -xzvf 1.9.32.6.tar.gz;cd /usr/local/src/publicnginx/nginx-1.8.0;service nginx stop;./configure --with-http_flv_module --with-ipv6 --with-http_mp4_module --with-pcre=../pcre-8.35 --sbin-path=/usr/local/sbin --conf-path=/etc/nginx/nginx.conf --pid-path=/var/run/nginx.pid --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --with-http_realip_module --with-http_ssl_module --http-client-body-temp-path=/tmp/nginx_client --http-proxy-temp-path=/tmp/nginx_proxy --http-fastcgi-temp-path=/tmp/nginx_fastcgi --with-http_stub_status_module --add-module=/usr/local/src/publicnginx/ngx_pagespeed-master;make install;reboot
Nota: El servidor se va a reiniciar, cuando suba entonces continuas con lo siguiente.
P5: Configurar PageSpeed
1) - En el WHM, vas a ir donde dice Nginx Admin, luego a "Configuración Editor", allí borraras todo lo que ya esta y pondrás lo siguiente & lo guardaras.
Insertar CODE, HTML o PHP:
user nobody;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
worker_rlimit_nofile 20480;
events {
worker_connections 2048;
use epoll;
}
http {
server_name_in_redirect off;
server_names_hash_max_size 10000;
server_names_hash_bucket_size 1024;
include mime.types;
default_type application/octet-stream;
server_tokens off;
#disable_symlinks if_not_owner;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 5;
gzip on;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
gzip_proxied any;
gzip_http_version 1.0;
gzip_min_length 1000;
gzip_comp_level 1;
gzip_buffers 16 8k;
gzip_types text/plain text/xml text/css application/x-javascript application/xml application/javascript application/xml+rss text/javascript application/atom+xml;
ignore_invalid_headers off;
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
reset_timedout_connection on;
connection_pool_size 256;
client_header_buffer_size 256k;
large_client_header_buffers 4 256k;
client_max_body_size 200M;
client_body_buffer_size 128k;
request_pool_size 32k;
output_buffers 4 32k;
postpone_output 1460;
proxy_temp_path /tmp/nginx_proxy/;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=microcache:15m inactive=24h max_size=500m;
client_body_in_file_only on;
log_format bytes_log "$msec $bytes_sent .";
log_format custom_microcache '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" nocache:$no_cache';
include "/etc/nginx/vhosts/*";
pagespeed on;
pagespeed FileCachePath /var/ngx_pagespeed_cache;
}
Insertar CODE, HTML o PHP:
nano /usr/local/cpanel/scripts/createvhosts.py
2) - Agrega las siguientes líneas al archivo createvhosts.py.
Buscar dedipvhost = """server { y agregar después.
Insertar CODE, HTML o PHP:
pagespeed on;
pagespeed FileCachePath /var/ngx_pagespeed_cache;
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
add_header "" "";
}
location ~ "^/pagespeed_static/" { }
Buscar sharedipvhost = """server { y agregar después, luego guardar.
Insertar CODE, HTML o PHP:
pagespeed on;
pagespeed FileCachePath /var/ngx_pagespeed_cache;
3) - En WHM, vas a Nginx Admin, luego le das a "Rebuild Vhosts" y listo.
P6: Instalando Varnish
OP1-> Si es CentOS 6.
Insertar CODE, HTML o PHP:
nano /etc/yum.repos.d/varnish.repo
Insertar CODE, HTML o PHP:
[varnish]
name=Varnish for Enterprise Linux
baseurl=https://repo.varnish-cache.org/redhat/varnish-3.0/el6/$basearch
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-VARNISH
Insertar CODE, HTML o PHP:
yum install varnish-3.0.7 -y;chkconfig varnish on
OP2-> Si es CentOS 7.
Insertar CODE, HTML o PHP:
nano /etc/yum.repos.d/varnish.repo
Insertar CODE, HTML o PHP:
[varnish]
name=Varnish for Enterprise Linux
baseurl=https://repo.varnish-cache.org/redhat/varnish-3.0/el7/$basearch
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-VARNISH
Insertar CODE, HTML o PHP:
yum install varnish-3.0.7 -y;chkconfig varnish on
¿Conectarlo con Nginx y PageSpeed?, fácil.
1) - En el WHM, en "Ajustar las configuraciones", buscas con f3 lo siguiente 0.0.0.0, cambias el puerto 8081 por 8080.
2) - Calentamos los motores.
Insertar CODE, HTML o PHP:
rm -rf /etc/sysconfig/varnish;nano /etc/sysconfig/varnish
pega el código y guarda...
Insertar CODE, HTML o PHP:
NFILES=131072
MEMLOCK=82000
NPROCS="unlimited"
RELOAD_VCL=1
# DAEMON_COREFILE_LIMIT="unlimited"
VARNISH_VCL_CONF=/etc/varnish/default.vcl
VARNISH_LISTEN_PORT=8081
VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1
VARNISH_ADMIN_LISTEN_PORT=6082
VARNISH_SECRET_FILE=/etc/varnish/secret
VARNISH_MIN_THREADS=50
VARNISH_MAX_THREADS=1000
VARNISH_THREAD_TIMEOUT=120
VARNISH_STORAGE_FILE=/var/lib/varnish/varnish_storage.bin
VARNISH_STORAGE_SIZE=5G
VARNISH_STORAGE="file,${VARNISH_STORAGE_FILE},${VARNISH_STORAGE_SIZE}"
VARNISH_TTL=120
DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
-f ${VARNISH_VCL_CONF} \
-T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
-t ${VARNISH_TTL} \
-w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \
-u varnish -g varnish \
-S ${VARNISH_SECRET_FILE} \
-s ${VARNISH_STORAGE}"
3) - Para que la vaina se ponga "sepsi", terminaras con lo siguiente.
Insertar CODE, HTML o PHP:
rm -rf /etc/varnish/default.vcl;nano /etc/varnish/default.vcl
paste..., cambia los 0.0.0.0 por el ip principal del servidor y finished.!
Insertar CODE, HTML o PHP:
backend default {
.host = "0.0.0.0";
.port = "8080";
}
if (req.restarts == 0) {
if (req.http.x-forwarded-for) {
set req.http.X-Forwarded-For =
req.http.X-Forwarded-For + ", " + client.ip;
} else {
set req.http.X-Forwarded-For = client.ip;
}
}
if (req.request != "GET" &&
req.request != "HEAD" &&
req.request != "PUT" &&
req.request != "POST" &&
req.request != "TRACE" &&
req.request != "OPTIONS" &&
req.request != "DELETE") {
return (pipe);
}
if (req.request != "GET" && req.request != "HEAD") {
return (pass);
}
if (req.http.Authorization || req.http.Cookie) {
return (pass);
}
return (lookup);
}
sub vcl_pipe {
return (pipe);
}
sub vcl_pass {
return (pass);
}
sub vcl_hash {
hash_data(req.url);
if (req.http.host) {
hash_data(req.http.host);
} else {
hash_data(server.ip);
}
return (hash);
}
sub vcl_hit {
return (deliver);
}
sub vcl_miss {
return (fetch);
}
sub vcl_fetch {
if (beresp.ttl <= 0s ||
beresp.http.Set-Cookie ||
beresp.http.Vary == "*") {
set beresp.ttl = 120 s;
return (hit_for_pass);
}
return (deliver);
}
sub vcl_deliver {
return (deliver);
}
sub vcl_error {
set obj.http.Content-Type = "text/html; charset=utf-8";
set obj.http.Retry-After = "5";
synthetic {"
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>"} + obj.status + " " + obj.response + {"</title>
</head>
<body>
<h1>Error "} + obj.status + " " + obj.response + {"</h1>
<p>"} + obj.response + {"</p>
<h3>Error Temporal ID:</h3>
<p>XID: "} + req.xid + {"</p>
<hr>
<p>Varnish Error</p>
</body>
</html>
"};
return (deliver);
}
sub vcl_init {
return (ok);
}
sub vcl_fini {
return (ok);
}
Ah otra cosa, si tienes varias ips dedicadas a varios sitios en tu caso sería el siguiente que vas a usar...
Insertar CODE, HTML o PHP:
backend default {
.host = 1.1.1.1";
.port = "8080";
}
backend otraip {
.host = "2.2.2.2";
.port = "8080";
}
sub vcl_recv {
if (server.ip == "1.1.1.1") {
set req.backend = default;
} else {
set req.backend = otraip;
}
if (req.restarts == 0) {
if (req.http.x-forwarded-for) {
set req.http.X-Forwarded-For =
req.http.X-Forwarded-For + ", " + client.ip;
} else {
set req.http.X-Forwarded-For = client.ip;
}
}
if (req.request != "GET" &&
req.request != "HEAD" &&
req.request != "PUT" &&
req.request != "POST" &&
req.request != "TRACE" &&
req.request != "OPTIONS" &&
req.request != "DELETE") {
return (pipe);
}
if (req.request != "GET" && req.request != "HEAD") {
return (pass);
}
if (req.http.Authorization || req.http.Cookie) {
return (pass);
}
return (lookup);
}
sub vcl_pipe {
return (pipe);
}
sub vcl_pass {
return (pass);
}
sub vcl_hash {
hash_data(req.url);
if (req.http.host) {
hash_data(req.http.host);
} else {
hash_data(server.ip);
}
return (hash);
}
sub vcl_hit {
return (deliver);
}
sub vcl_miss {
return (fetch);
}
sub vcl_fetch {
if (beresp.ttl <= 0s ||
beresp.http.Set-Cookie ||
beresp.http.Vary == "*") {
set beresp.ttl = 120 s;
return (hit_for_pass);
}
return (deliver);
}
sub vcl_deliver {
return (deliver);
}
sub vcl_error {
set obj.http.Content-Type = "text/html; charset=utf-8";
set obj.http.Retry-After = "5";
synthetic {"
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>"} + obj.status + " " + obj.response + {"</title>
</head>
<body>
<h1>Error "} + obj.status + " " + obj.response + {"</h1>
<p>"} + obj.response + {"</p>
<h3>Error Temporal ID:</h3>
<p>XID: "} + req.xid + {"</p>
<hr>
<p>Error Varnish</p>
</body>
</html>
"};
return (deliver);
}
sub vcl_init {
return (ok);
}
sub vcl_fini {
return (ok);
}
Insertar CODE, HTML o PHP:
reboot
¿Dudas, Preguntas, Ayuda? Por privado pásame tu Skype o GTalk y hablemos 😛 y/o comenta en el tema en caso de problemas/errores para resolverlos en 3 segundos, te ayudo totalmente gratis en caso de que no tengas conocimiento de cómo hacer esto pero el caso de hacer esto para servers adicionales podría llevar a un costo por trabajo.
Con esto tu sitio web va a volar mas rápido que contratar a un Sysadmin para optimizar un servidor de 32 cores con 256gb de ram... 😉
Saluditos.
Última edición: