Virtual Hosting in Apache (Part 2)
Oct 11, 07 by Juan Lebrijo about Web, blog
Continuing qith the second part about my Apache Virtual Hosting experience. You can read first in: Apache Virtual Hosting (Parte 1). We can see how our Apache serves remote server pages encrypted with SSL and un-encrypted.

Redirect to other web server

With this estrategy we can serve other server content as this contents are in our server. It is a web proxy, but for one determined site. It can take various uses:
  • Serve towards internet a local server filtered because of security.
  • Serve from internet some beyond server to win in speed.
  • If you think another put a comment.
To use the following directives we must enabled the proxy module mod_proxy. How is enable in Apache2:
elite:~# cd /etc/apache2/mods-enabled/
elite:/etc/apache2/mods-enabled# ln -s ../mods-available/proxy.conf proxy.conf
elite:/etc/apache2/mods-enabled# ln -s ../mods-available/proxy.load proxy.load
elite:/etc/apache2/mods-enabled# ln -s ../mods-available/proxy_http.load proxy_http.load
elite:/etc/apache2/mods-enabled# /etc/init.d/apache restart
The code:
<VirtualHost *>
        ServerName privado.tudominio.com

        ProxyPreserveHost On
        ProxyRequests Off
        <Proxy *>
                Order deny,allow
                Allow from all
        </Proxy>
        ProxyPass / http://192.168.0.1/
        ProxyPassReverse / http://192.168.0.1/
</VirtualHost>
ServerName is how it be called from intenet (http://privado.tudominio.com) to this content (http://192.168.0.1/) of local network. <Proxy> directive set the permissions to the object. And directives as ProxyPass (mapping extern direction) and ProxyPassReverse (adjusting the URL to HTTP Location field) fix us the direction (IP or DNS) that we want map.

Redirect to another web server, but secure https

Even more dificult, we want that Apache acts as proxy or secure remote server. Installing webmin which provides of a secure server on port 10000, I cocluded that was beter redirect with this estrategy than change webmin to apache. Of course ssl and proxy modules must be installed, mod_ssl y mod_proxy (installed at previous point):
elite:~# cd /etc/apache2/mods-enabled/
elite:/etc/apache2/mods-enabled# ln -s ../mods-available/ssl.conf ssl.conf
elite:/etc/apache2/mods-enabled# ln -s ../mods-available/ssl.load ssl.load
elite:/etc/apache2/mods-enabled# /etc/init.d/apache restart
Virtual Host configuration would be:
<VirtualHost *>
        ServerName webmin.tudominio.com

        ProxyRequests Off
        SSLProxyEngine On
        ProxyVia On
        <Proxy *>
                AddDefaultCharset off
                Order deny,allow
                Allow from all
        </Proxy>

        ProxyPass / https://localhost:10000/
        ProxyPassReverse / https://localhost:10000/
        ProxyPassReverseCookieDomain localhost:10000 tudominio.com
        ProxyPassReverseCookiePath / /
</VirtualHost>
The same explication as previous point but caching the SSL certificates with  SSLProxyEngine tag, and futherore the cookies with last tags.
Virtual Hosting in Apache (Part 1)
Oct 08, 07 by Juan Lebrijo about Web, blog
If we want to publish various domains, we would not need the same number of servers as domains. With Apache Virtual Hosting we can have all domains we need in one server. Today is the firs part to deploy in practice this subject, in some days we will have the second part: Apache Virtual Hosting (Part 2). There are two virtual hosting types:
  • Name based: One IP to various domains.
  • IP based: Every domain have its IP, every IPs as network interfaces have our server.
Usually (in hme servers) we take the name-based hosting, therefore we host more than one domain, or subdomains, or host other domains and portals (I hope with payment). It happens to me, then I am going to tell you my experience in some cases and concrete applications. In Apache2 we can adminitrate virtual hosting in a directory. Then we can do so many files as hosted sites you have in the file /etc/apache2/sites-available/default.

Basic site: www

The site www.tudominio.com is a subdomain in tudominio.com, therefore this example runs for blog.tudominio.com, motos.tudominio.com,.... BE CAREFUL: Never forget type your domain in your DNS server (you can study in depth here); or throug your Domain Register if you do not have DNS server. The tag basic structure is:
<VirtualHost *>
        ServerAdmin webmaster@tudominio.com
        ServerName www.tudominio.com
        ServerAlias tudominio.com
        DocumentRoot /var/www/tudominio

        ErrorLog /var/log/apache2/error.log
        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access.log combined
        ServerSignature On
</VirtualHost>
Commentin the tags one by one:
  • ServerAdmin: Web server administrator mail.
  • ServerName: What domain name petitions server must reply.
  • ServerAlias: Solve errors, as forgetful clients who forget typing www.
  • DocumentRoot: directory where I copy my published data.
  • ErrorLog: Log where the daemon type the errors. So we do not abuse of syslog.
  • LogLevel: Detail level for the errors receptioned.
  • CustomLog: Log where type your clients accessed.
  • ServerSignature: Autogenerated pages final signature; where usually appends the operating system, web server, verions, etc.

Redirection to a executable cgi out of web tree

For example we can publish the charge lever of an UPS; the manufacturer provides a cgi:
<VirtualHost *>
        ServerName sistema.tudominio.com
        DocumentRoot /var/www/tudominio/sistema

        ScriptAlias /sai/ "/usr/lib/cgi-bin/nut/"
        <Directory "/usr/lib/cgi-bin/nut">
                AllowOverride None
                Options +ExecCGI
                Order allow,deny
                Allow from all
        </Directory>

</VirtualHost>
We have the the two first lines the name for the domain of the response, and the rrot directory. Really al this the estrategy is in ScriptAliastag and the Directory directive, wich be able to  be hoste in every domain:
  • ScriptAlias: Is the nick (/sai/) which will be the directory where are hosted our cgi's.
  • Directory: Only specifies how i managed a directory out of the tree.
In this way we call from our web browser to the cgi file as follows: http://sistema.tudominio.com/sai/ejecutable.cgi You can continue the second part of this subject in the link: Apache Virtual Hosting (Part 2).
Hosting Virtual en Apache (Parte I)
Oct 08, 07 by Juan Lebrijo about Services, Web, blog
Si queremos publicar varios dominios, no haría falta tener tantos servidores como dominios. Con el Virtual Hosting de Apache podríamos montar tantos dominios como quisieramos en un servidor. Hoy es la primera entrega para desarrollar de forma práctica esta temática, dentro de unos días aparecerá en este blog la segunda entrega: Hosting Virtual en Apache (Parte II). Hay dos tipos de Hosting Virtual:
  • El basado en Nombre: con una IP sirves varios dominios.
  • El basado en IP: Cada dominio puede tener su IP, tantas IP como interfaces de red tenga instalado nuestra máquina.
Lo normal (en los que a servidores caseros se refiere) es hacer el "basado en Nombre" ya que nos solemos liar y hacer más de un portal web en nuestro dominio, ó incluso alojar otros portales (espero que lo hagais previo pago). A mi me ha pasado, naturalmente, y os voy a contar mis peripecias con varios casos y aplicaciones concretas. En Apache2 los virtual hosts se administran en un directorio. De forma que podeis hacer include de tantos ficheros como sitios tengais en el archivo /etc/apache2/sites-available/default.

Sitio básico: www

El sitio www.tudominio.com es un subdominio en realidad de tudominio.com, por tanto este ejemplo sirve para blog.tudominio.com, motos.tudominio.com,.... OJO: Eso sí nunca debeis olvidar dar de alta el subdominio en vuestro Servidor DNS (podeis ver más detalladamente como aquí); ó si no teneis servidor propio hacerlo a través de vuestro registrador de dominio. La estructura básica de la etiqueta es:
<VirtualHost *>
        ServerAdmin webmaster@tudominio.com
        ServerName www.tudominio.com
        ServerAlias tudominio.com
        DocumentRoot /var/www/tudominio

        ErrorLog /var/log/apache2/error.log
        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access.log combined
        ServerSignature On
</VirtualHost>
Comentando las etiquetas una a una tenemos:
  • ServerAdmin: Correo del administrador del servidor web.
  • ServerName: A que peticiones de nombre de dominio a este servidor debo responder.
  • ServerAlias: Esta etiqueta es para resolver errores, como los xlientes olvidadizos que se olvidan de poner la www.
  • DocumentRoot: el directorio donde alojemos el contenido que queremos publicar.
  • ErrorLog: El log donde queremos que apunte los fallos. Así no inundamos el general, y no se convierte en inmanejable.
  • LogLevel: El nivel de detalle de errores que queremos que recoja.
  • CustomLog: El log donde se apunta quien accede a tu sitio.
  • ServerSignature: La línea final en las páginas autogeneradas; donde se indica el sistema operativo, servidor web, versiones, etc.

Redirigir a un ejecutable cgi fuera del arbol web

Por ejemplo para publicar la páqina de carga de un sai; el software que te proporciona el fabricante es un cgi:
<VirtualHost *>
        ServerName sistema.tudominio.com
        DocumentRoot /var/www/tudominio/sistema

        ScriptAlias /sai/ "/usr/lib/cgi-bin/nut/"
        <Directory "/usr/lib/cgi-bin/nut">
                AllowOverride None
                Options +ExecCGI
                Order allow,deny
                Allow from all
        </Directory>

</VirtualHost>
Tenemos en las dos primeras líneas el nombre para el dominio sobre el que se responderá al alias, y el directorio base. En realidad el grueso de esta estrategia está en la etiqueta ScriptAlias y la directiva Directory, que pueden estar en cualquier dominio planteado:
  • ScriptAlias: Dice el sobrenombre (/sai/) que va a poner al directorio donde se alojan nuestros cgi's.
  • Directory: Simplemente especifica como manejar este directorio externo al arbol.
De esta forma llamaremos desde el cliente web a nuestro cgi de la siguiente manera: http://sistema.tudominio.com/sai/ejecutable.cgi Podeis continuar con la segunda entrega de este artículo en el enlace: Hosting Virtual en Apache (Parte II).