Caching configuración utilizando Apache 1.3
limi
Asegúrese de tener instalado un servidor web Apache. Esta configuración
en particular está basada en Apache 1.3. Para otros servidores de web,
mirar las siguientes páginas en este tutorial.
Asegúrese que Apache esta corriendo sobre el puerto 80 para comprobar esto puede ver la página por defecto de Apache en http://site.com.
Debemos editar el archivo de configuración de Apache (normalmente localizado en /etc/httpd/conf/httpd.conf - si usted no sabe donde se encuentra el archivo de configuración, usar locate httpd.conf), ahí hay algunas cosas que usted tendrá que checkear:
- Asegúrese que
mod_proxyesta habilitado. Busque la lista de módulos cargados para libproxy.so, y asegure que las siguientes líneas no están comentadas:
LoadModule proxy_module modules/libproxy.so
AddModule mod_proxy.c - Configurar
un VirtualHost para su nombre de dominio que use un reverse-proxy en
orden de pasar las peticiones a través de Zope. El siguiente ejemplo
puede ser copiado y pegado en la parte de más abajo de su archivo de
configuración, y usted solo tendrá que editar un par de líneas:
<VirtualHost *>
# A sample VirtualHost section for using Apache as a webserver
# instead of Zope.
# ServerName is the url of your website.
ServerName site.com
# Add serverAlias lines for other domain names that should
# point to this website. They will be rewritten by Apache to
# the ServerName, so that anyone going to www.site.com
# will be invisibly redirected to site.com in their browser.
ServerAlias www.site.com
# ServerAdmin is your email address, which shows up on error
# pages when Apache cannot connect to Zope.
ServerAdmin webmaster@site.com
# The ProxyPass and ProxyPassReverse lines are the magic
# ingredients. They rewite requests to http://site.com and
# pass the entire request through to Zope on
# http://site.com:8080. The VirtualHostBase ensures that
# when the page goes back to the browser, it goes out through
# Apache, and appears to have come from http://site.com.
# The line is made up from:
# ProxyPass or ProxyPassReverse
# / is the url at http://site.com that you wish to use to
# point to the Zope site. You could keep http://site.com as a
# flat HTML site in Apache, and replace / with /zope to make
# http://site/com/zope point to your zope site.
# http://site.com:8080 is the address that your zope is
# running on.
# /VirtualHostBase/http/site.com:80 makes sure that zope
# *thinks* it is running at http://site.com instead of at
# http://site.com:8080. You don't have to do anything else
# in Zope to make this work.
# /yourplonesite is the location of your Plone Site within Zope.
# If you added a Plone Site into the root of your Zope with an id
# of 'mysite', then you just change this bit to /mysite
# /VirtualHostRoot/ makes your Plone site think it is the root of the site.
ProxyPass / http://site.com:8080/VirtualHostBase/http/site.com:80/plonesite/VirtualHostRoot/
ProxyPassReverse / http://site.com:8080/VirtualHostBase/http/site.com:80/plonesite/VirtualHostRoot/
</VirtualHost>
/etc/httpd/modules/.)Ahora usted tiene una configuración respetable: Apache esta sirviendo las peticiones web y Zope es un servidor backend. Como bonus, también tiene un virtual hosting completamente configurado, por lo tanto puede correr múltiples sitios diferentes con múltiples dominios diferentes sobre un solo servidor con una sola dirección de IP. Todo lo que necesita hacer es duplicar y editar esa sección del VirtualHost por cada sitio.
Usted quería tomar nota sobre que tan rápido esta corriendo esta configuración hasta este punto. Notar que no hemos ganado ninguna verdadera ventaja de velocidad aun, nosotros solo hemos puesto los fundamentos para esto. En una terminal, usar la aplicación Apache Benchmark para probar la velocidad del sitio. La aplicación se encuentra normalmente en '/usr/sbin/ab':
/usr/sbin/ab -n 100 http://yoursite.com/Esto va a pedir consecutivamente 100 solicitudes a su servidor. Usted debería notar que todas las solicitudes toman cerca de 0.5 a 1.0 segundos, con no mucha discrepancia. Mientas esto no parece tan malo para una pagina dinámica, recuerde que esto es solo el HTML. Para una página completa con CSS, Javascript e imágenes el tiempo de procesamiento puede ser mucho mas largo.
La salida típica podría parecerse a esto:
Benchmarking site.com (be patient).....doneEntonces, que podemos hacer para hacerlo mas rapido?
Server Software: Zope
Server Hostname: site.com
Server Port: 80
Document Path: /
Document Length: 32560 bytes
Concurrency Level: 1
Time taken for tests: 68.901 seconds
Complete requests: 100
Failed requests: 0
Broken pipe errors: 0
Total transferred: 3293500 bytes
HTML transferred: 3256000 bytes
Requests per second: 1.45 [#/sec] (mean)
Time per request: 689.01 [ms] (mean)
Time per request: 689.01 [ms] (mean, across all concurrent requests)
Transfer rate: 47.80 [Kbytes/sec] received
Lo primero que podemos hacer es permitir a Apache que cache el resultado de las páginas. Esto puede hacerse porque configuramos Apache para ser el servidor front-end, nosotros en realidad hemos creado un
caching reverse-proxy,
lo que significa que todas las páginas que produce Zope son ahora
llevadas de nuevo afuera al navegador a través de Apache y pueden ser
cacheadas para incrementar dramáticamente el funcionamiento. Solo que
aun no le hemos dicho a Apache que cache algo aun.Para dejar que Apache conozca que deseamos cachear contenido con un cierto tiempo de expiración, el archivo mod_expires debe ser instalado. Compruebe su directorio de módulos de Apache (normalmente
/etc/httpd/modules) para mod_expires.so, y luego asegúrese de tener las siguientes líneas en el archivo de configuración de su Apache:LoadModule expires_module modules/mod_expires.soAl final de la sección VirtualHost, justo antes de
AddModule mod_expires.c
</VirtualHost> añadir las siguientes líneas:# CacheRoot is the location on the filesystem to store files thatUna vez que usted ha terminado de añadir esto a la sección VirtualHost, guardar el archivo config. Ahora, entre a su carpeta
# Apache caches. This directory must be created, and the user that
# Apache runs as must have full write permissions to it.
# It's a bad idea to create this in the /tmp directory, as the
# directory itself will then be deleted when you reboot.
CacheRoot "/var/cache/site.com"
# CacheSize determines how big this cache can get in KB. It's a
# good idea that this number is about 30% less than the available
# space in the CacheRoot directory. Here we choose to cache 10MB
# of data, which is enough for a personal website, but not for
# anything larger.
CacheSize 10000
# CacheGcInterval specifies how often (in hours) to examine the
# cache and delete obsolete files.
CacheGcInterval 2
# CacheLastModifiedFactor allows the estimation of an expiry date
# for a page if it doesn't have an expiry-date specified in the
# HTTP headers returned from Zope. This is based on (time since
# last modification * CacheLastModifiedFactor), so that content
# that is ten hours old would be given an expiry date of 1 hour in
# the future.
CacheLastModifiedFactor 0.1
# CacheDefaultExpire sets a default expiry time of 1 hour into the
# future for cached pages.
CacheDefaultExpire 1
# CacheDirLength sets the number of characters used in directory
# names for subdirectories of CacheRoot
CacheDirLength 2
# The following definitions set expiry times for various content
# types. In this list, each content type defined is cached for a
# maximum period of 1 hour (3600 seconds) before it must be checked
# again. Non-listed content types are not cached.
ExpiresActive On
ExpiresByType image/gif A3600
ExpiresByType image/png A3600
ExpiresByType image/jpeg A3600
ExpiresByType text/css A3600
ExpiresByType text/javascript A3600
ExpiresByType application/x-javascript A3600
ExpiresByType text/html A3600
ExpiresByType text/xml A3600
/var/cache, cree el directorio definido como CacheRoot
en la configuración que usted acaba de editar y haga este escribible
para el usuario apache. En el caso de nuestro ejemplo, esto seria:mkdir /var/cache/site.comAhora reinicia Apache para asegurarnos que estos cambios han tenido efecto:
chown -R apache:apache /var/cache/site.com
apachectl gracefulHasta este punto, aunque Apache sea capaz de realizar caching, ninguna de sus páginas en realidad están siendo cacheadas. Podemos probar esto usando wget y mostrando los HTTP Response headers:
wget -sS --delete-after http://site.com/Note el X-Cache header mostrando un cache
--03:16:51-- http://site.com/
=> `index.html'
Resolving site.com... done.
Connecting to site.com[127.0.0.1]:80... connected.
HTTP request sent, awaiting response...
1 HTTP/1.1 200 OK
2 Date: Mon, 19 Jan 2004 03:16:51 GMT
3 Server: Zope/(unreleased version, python 2.3.2, linux2) ZServer/1.1 Plone/2.0-RC3
4 Vary: Accept-Encoding
5 Content-Length: 32560
6 Content-Language:
7 Expires: Mon, 19 Jan 2004 04:16:52 GMT
8 Etag:
9 Cache-Control: max-age=3600
10 Content-Type: text/html;charset=utf-8
11 X-Cache: MISS from site.com
12 Connection: close
MISS.
Mientras nosotros esperamos esto la primera vez que llamamos una página
(como esto aún no ha sido cacheada), ahora esperaríamos llamadas
subsecuente a aquella página si el caching esta trabajando de manera
correcta.
Su sistema esta ahora en el punto donde es
totalmente capaz de cachear contenido y todo lo que resta por hacer es
decirle a su Accelerated HTTP Cache Manager en su sitio Plone que es lo
que debería cachear.