Servidor Web Lighttpd + PHP =========================== .. contents:: Tabla de contenidos .. image:: _images/light_logo.png :align: right :width: 200px 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 ----------------------- .. code:: shell 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: .. code:: shell 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: .. code:: shell sudo nano /etc/lighttpd/lighttpd.conf Comprobamos que aparecen las dos primeras líneas y que la tercera incluye index.php: .. code-block:: shell 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: .. code:: shell sudo service lighttpd restart Añadimos las siguiente linea para que el servidor se inicie al arrancar el sistema: .. code:: shell sudo systemctl enable lighttpd Verificamos el estado de Lighttpd: .. code:: shell sudo systemctl status lighttpd .. code-block:: shell ? 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: .. image:: _images/lighttpd3.png :align: center Esto significa que nuestro servidor web ya está en funcionamiento. Instalación de PHP ------------------ .. image:: _images/php7.jpg :align: right :width: 250px A continuación, instalamos PHP, PHP-FPM y FastCGI en su sistema. Por defecto, Raspbian "buster" se entrega con PHP versión 7.3. .. code:: shell 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: .. code:: shell sudo nano /etc/php/7.3/fpm/php.ini Cambie la siguiente línea: .. code:: shell 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. .. code:: shell sudo nano /etc/php/7.3/fpm/pool.d/www.conf Buscamos la línea: .. code:: shell listen = /run/php/php7.3-fpm.sock Y reemplazarla por la siguiente: .. code:: shell listen = 127.0.0.1:9000 Guardamos y salimos. Luego, reiniciamos el servicio PHP-FPM para aplicar los cambios de configuración: .. code:: shell sudo systemctl restart php7.3-fpm A continuación tenemos que modificar el fichero ``15-fastcgi-php.conf`` .. code:: shell sudo nano /etc/lighttpd/conf-available/15-fastcgi-php.conf Buscamos las siguientes líneas: .. code:: shell "bin-path" => "/usr/bin/php-cgi", "socket" => "/var/run/lighttpd/php.socket", Y las reemplazamos por: .. code:: shell "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: .. code:: shell lighty-enable-mod fastcgi lighty-enable-mod fastcgi-php Reiniciamos lighttpd .. code:: shell sudo systemctl restart lighttpd Ahora creamos un nuevo archivo de host virtual para probar PHP con Lighttpd. .. code:: shell sudo nano /etc/lighttpd/conf-available/example.com.conf Añadimos el siguiente código: .. code-block:: shell $HTTP["host"] == "www.example.com" { server.document-root = "/var/www/html/" server.errorlog = "/var/log/lighttpd/example.com-error.log" } Habilitamos el Virtual host .. code:: shell 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: .. code:: shell sudo apt-get install software-properties-common sudo add-apt-repository ppa:certbot/certbot Actualizamos e instalamos: .. code:: shell sudo apt-get update -y sudo apt-get install certbot -y Creamos el certificado Let’s Encrypt .. code:: shell 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: .. code-block:: shell 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: .. code-block:: console 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: .. code-block:: console 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. .. code:: shell sudo nano /etc/lighttpd/conf-enabled/example.com.conf Cambie el archivo como se muestra a continuación: .. code-block:: shell $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 .. code:: shell sudo systemctl restart lighttpd Ya podemos mostrar ficheros PHP. Para comprobarlo, creamos un archivo de prueba llamado, por ejemplo, ``prueba.php``: .. code:: shell cd /var/www/html sudo nano prueba.php en el que incluiremos este sencillo contenido: .. image:: _images/captura1.png Guardamos y cerramos. A continuación cambiamos la propiedad del directorio root para lighttpd a www-data: .. code:: shell sudo chown -R www-data:www-data /var/www/html/ Y reiniciamos: .. code:: shell 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: .. image:: _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.