Servidor Web Lighttpd + PHP

_images/light_logo.png

Introducción

Lighttpd es posiblemente el servidor web más liviano que hay disponible en la actualidad. Esto significa que consume muy pocos recursos de la máquina en la que se instala. Y por este motivo muchos usuarios lo eligen para montar un servidor web en su Raspberry Pi. Veamos cómo sería el proceso.

Instalación de lighttpd

sudo apt-get install lighttpd

Vamos ahora a cambiar el propietario y el grupo de la carpeta /var/www/html y a añadir al usuario pi a dicho grupo:

sudo chown www-data:www-data /var/www/html
sudo chmod 775 /var/www/html
sudo usermod -a -G www-data pi

Editamos el fichero de configuración de Lighttpd:

sudo nano /etc/lighttpd/lighttpd.conf

Comprobamos que aparecen las dos primeras líneas y que la tercera incluye index.php:

server.username = "www-data"
server.groupname = "www-data"
index-file.names = ("index.html", "index.lighttpd.html", "index.php")

Si no fuera así, las añadimos. Y ahora reiniciamos el servidor:

sudo service lighttpd restart

Añadimos las siguiente linea para que el servidor se inicie al arrancar el sistema:

sudo systemctl enable lighttpd

Verificamos el estado de Lighttpd:

sudo systemctl status lighttpd
? lighttpd.service - Lighttpd Daemon
Loaded: loaded (/lib/systemd/system/lighttpd.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2019-09-06 02:09:35 EDT; 29s ago
Main PID: 4445 (lighttpd)
    Tasks: 1 (limit: 1138)
Memory: 1.4M
CGroup: /system.slice/lighttpd.service
        ??4445 /usr/sbin/lighttpd -D -f /etc/lighttpd/lighttpd.conf

Sep 06 02:09:35 debian systemd[1]: Starting Lighttpd Daemon...
Sep 06 02:09:35 debian systemd[1]: Started Lighttpd Daemon.
Sep 06 02:09:36 debian systemd[1]: /lib/systemd/system/lighttpd.service:6: PIDFile= references path below legacy directory /var/run/, updating
lines 1-12/12 (END)

Ahora si escribimos la IP local en el navegador del PC (http://192.168.1.33), por ejemplo, veremos una página web de ejemplo similar a esta:

_images/lighttpd3.png

Esto significa que nuestro servidor web ya está en funcionamiento.

Instalación de PHP

_images/php7.jpg

A continuación, instalamos PHP, PHP-FPM y FastCGI en su sistema. Por defecto, Raspbian «buster» se entrega con PHP versión 7.3.

sudo apt-get install php php-cgi php-fpm php-mysql -y

Una vez que todos los paquetes estén instalados, deberá editar el archivo php.ini y establecer cgi.fix_pathinfo en 1. Puede hacerlo con el siguiente comando:

sudo nano /etc/php/7.3/fpm/php.ini

Cambie la siguiente línea:

cgi.fix_pathinfo=1

Por defecto, PHP apunta a UNIX Socket /var/run/php/php7.3-fpm.sock. Por lo tanto, tenemos que modificar el grupo PHP-FPM para configurar las escuchas PHP en TCP Socket.

sudo nano /etc/php/7.3/fpm/pool.d/www.conf

Buscamos la línea:

listen = /run/php/php7.3-fpm.sock

Y reemplazarla por la siguiente:

listen = 127.0.0.1:9000

Guardamos y salimos. Luego, reiniciamos el servicio PHP-FPM para aplicar los cambios de configuración:

sudo systemctl restart php7.3-fpm

A continuación tenemos que modificar el fichero 15-fastcgi-php.conf

sudo nano /etc/lighttpd/conf-available/15-fastcgi-php.conf

Buscamos las siguientes líneas:

"bin-path" => "/usr/bin/php-cgi",
"socket" => "/var/run/lighttpd/php.socket",

Y las reemplazamos por:

"host" => "127.0.0.1",
"port" => "9000",

Salvamos y cerramos, a continuación habilitamos los módulos FastCGI y FastCHI-PHP con los siguientes comandos:

lighty-enable-mod fastcgi
lighty-enable-mod fastcgi-php

Reiniciamos lighttpd

sudo systemctl restart lighttpd

Ahora creamos un nuevo archivo de host virtual para probar PHP con Lighttpd.

sudo nano /etc/lighttpd/conf-available/example.com.conf

Añadimos el siguiente código:

$HTTP["host"] == "www.example.com" {
    server.document-root = "/var/www/html/"
    server.errorlog      = "/var/log/lighttpd/example.com-error.log"
}

Habilitamos el Virtual host

ln -s /etc/lighttpd/conf-available/example.com.conf /etc/lighttpd/conf-enabled/

Securizando Lighttpd con certificado gratuito Let’s Encrypt

Primero, debemos instalar la herramienta Certbot para asegurar nuestro servidor web con Let’s Encrypt. Por defecto, la última versión de Certbot no está disponible en el repositorio predeterminado de Raspbian 10 (buster).

Añadimos las fuentes al repositorio:

sudo apt-get install software-properties-common
sudo add-apt-repository ppa:certbot/certbot

Actualizamos e instalamos:

sudo apt-get update -y
sudo apt-get install certbot -y

Creamos el certificado Let’s Encrypt

certbot certonly --webroot -w /var/www/html/ -d www.example.com

Nos pedirá que aportemos una dirección de correo electrónico y acepte el plazo de la licencia:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator webroot, Installer None
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): admin@example.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

Una vez que los certificados se descargan correctamente, deberiamos ver el siguiente resultado:

IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/example.com/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/example.com/privkey.pem
Your cert will expire on 2019-12-06. To obtain a new or tweaked
version of this certificate in the future, simply run certbot
again. To non-interactively renew *all* of your certificates, run
"certbot renew"
- If you like Certbot, please consider supporting our work by:

Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
Donating to EFF:                    https://eff.org/donate-le

A continuación, tenemos que combinar el certificado y la clave privada en un archivo:

cat /etc/letsencrypt/live/example.com/cert.pem
/etc/letsencrypt/live/example.com/privkey.pem >
/etc/letsencrypt/live/example.com/web.pem

A continuación, deberá editar el archivo de host virtual Lighttpd y definir la ruta del certificado Let’s Encrypt SSL.

sudo nano /etc/lighttpd/conf-enabled/example.com.conf

Cambie el archivo como se muestra a continuación:

$HTTP["host"] == "www.example.com" {
    server.document-root = "/var/www/html/"
}

$SERVER["socket"] == ":443" {
ssl.engine = "enable"
ssl.pemfile = "/etc/letsencrypt/live/example.com/web.pem" # Combined Certificate
ssl.ca-file = "/etc/letsencrypt/live/example.com/chain.pem" # Root CA
server.name = "www.example.com" # Domain Name OR Virtual Host Name
server.document-root = "/var/www/html/" # Document Root
server.errorlog = "/var/log/lighttpd/example.com_error.log"
accesslog.filename = "/var/log/lighttpd/example.com_access.log"
}

$HTTP["scheme"] == "http" {
$HTTP["host"] == "www.example.com" { # HTTP URL
url.redirect = ("/.*" => "https://www.example.com$0") # Redirection HTTPS URL
}
}

Guardamos y cerramos el editor y reiniciamos lighttpd

sudo systemctl restart lighttpd

Ya podemos mostrar ficheros PHP. Para comprobarlo, creamos un archivo de prueba llamado, por ejemplo, prueba.php:

cd /var/www/html
sudo nano prueba.php

en el que incluiremos este sencillo contenido:

_images/captura1.png

Guardamos y cerramos. A continuación cambiamos la propiedad del directorio root para lighttpd a www-data:

sudo chown -R www-data:www-data /var/www/html/

Y reiniciamos:

sudo systemctl restart lighttpd

Como antes, si abrimos en el navegador del PC la IP local de la Raspberry con https, seguida del nombre del fichero PHP que hemos creado https://mipagina/test.php, nos aparecerá un cuadro con información detallada sobre la versión de PHP instalada:

_images/secure.jpg

Las páginas web que queramos mostrar hemos de colocarlas en el directorio /var/www/html y además tendremos que abrir el puerto 80 en el router y dirigirlo a la IP local de la RasPi para poder acceder desde Internet al servidor.