Diferencia entre revisiones de «LEMP»
Sin resumen de edición |
Sin resumen de edición |
||
| Línea 272: | Línea 272: | ||
* Configurar contraseñas: | * Configurar contraseñas: | ||
Si se quiere configurar contraseñas Auth Basic se almacenan en /etc/nginx/passwd | Si se quiere configurar contraseñas Auth Basic se almacenan en /etc/nginx/passwd. | ||
<syntaxhighlight lang="Bash">mkdir /etc/nginx/passwd</syntaxhighlight> | |||
Por ejemplo: | |||
<syntaxhighlight lang="Bash">htpasswd -c -B /etc/nginx/passwd/test.pw guzman</syntaxhighlight> | |||
* Configurar snippets: | * Configurar snippets: | ||
| Línea 297: | Línea 300: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="Bash">vi /etc/nginx/snippets/denied.conf</syntaxhighlight> | |||
<syntaxhighlight lang="text"> | |||
# Deny *.txt, *.log, .*/*.php, .*, *.json, .lock, *.ht | |||
# Not allow txt or logs to be downloaded | |||
location ~* \.(txt|log)$ { | |||
deny all; | |||
} | |||
# Not allow execute php in hidden folders | |||
location ~ \..*/.\.php$ { | |||
return 403; | |||
} | |||
# Not allow "hidden files" | |||
location ~ (^|/)\. { | |||
return 403; | |||
} | |||
# Not allow *.json or *.lock | |||
location ~* \.(json|lock)$ { | |||
return 403; | |||
} | |||
# Deny *.ht | |||
location ~ /\.ht { | |||
deny all; | |||
} | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="Bash">vi /etc/nginx/snippets/hsts.conf</syntaxhighlight> | |||
<syntaxhighlight lang="text"> | |||
# Activate HSTS (HTTP Strict Transport Security) | |||
# Note: if we set another header in a location we've to | |||
# rewrite it | |||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; | |||
</syntaxhighlight> | |||
* Configurar sites-available: | |||
En al carpeta /etc/nginx/sites-available/ se almacenan todos los Virtual Hosts disponibles. | |||
En Nginx hay que personalizar cada uno por cada tipo de aplicación. | |||
Hay que tener en cuenta las diferentes URL's. | |||
* Configurar sites-enabled: | |||
Se suelen configurar enlaces simbólicos con la carpeta sites-available para activarlos. | |||
Por ejemplo: | |||
<syntaxhighlight lang="Bash">ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default</syntaxhighlight> | |||
* Reiniciar Nginx: | |||
<syntaxhighlight lang="Bash">systemctl restart nginx</syntaxhighlight> | |||
== Configuración MariaDB == | |||
* Conectar a MariaDB | |||
<syntaxhighlight lang="Bash">mariadb</syntaxhighlight> | |||
* Opción 1: Permitir conexiones por TCP (sólo desde localhost) | |||
<syntaxhighlight lang="Sql"> | |||
grant all privileges on *.* to 'root'@'localhost' identified by 'password' with grant option; | |||
FLUSH PRIVILEGES; | |||
</syntaxhighlight> | |||
* Opción 2: Permitir conexiones por Sockets UNIX (sólo desde localhost) | |||
<syntaxhighlight lang="Sql"> | |||
grant all privileges on *.* to 'root'@'localhost' identified via unix_socket with grant option; | |||
FLUSH PRIVILEGES; | |||
</syntaxhighlight> | |||
Nota: esta opción es la que suelo usar yo (no se pueden usar los dos a la vez). | |||
[[Categoría:Notas]] | [[Categoría:Notas]] | ||
Revisión del 22:58 23 feb 2026
Instalación servidor LEMP
Instalaremos:
- GNU Linux (Ubuntu Server 24.04)
- eNginx 1.24.0 (APT Ubuntu)
- MariaDB 10.8 (Repo oficiales de MariaDB)
- PHP 8.5 (PPA ondrej/php)
Permisos de root
Todos los comandos en esta guía se realizarán como root.
sudo -i
Instalación Nginx (Stable)
- Actualizar repositorio
apt update
- Instalar Nginx
apt install nginx
- Instalación Apache Utils
apt install apache2-utils
Instalación MariaDB
- Instalar requisitos
apt install apt-transport-https curl
- Añadir repositorios MariaDB (oficiales)
mkdir -p /etc/apt/keyrings
curl -o /etc/apt/keyrings/mariadb-keyring.pgp 'https://mariadb.org/mariadb_release_signing_key.pgp'
vi /etc/apt/sources.list.d/mariadb.sources
# MariaDB 11.8 repository list - created 2026-02-23 08:31 UTC
# https://mariadb.org/download/
X-Repolib-Name: MariaDB
Types: deb
# deb.mariadb.org is a dynamic mirror if your preferred mirror goes offline. See https://mariadb.org/mirrorbits/ for details.
# URIs: https://deb.mariadb.org/11.8/ubuntu
URIs: https://mirror.raiolanetworks.com/mariadb/repo/11.8/ubuntu
Suites: noble
Components: main main/debug
Signed-By: /etc/apt/keyrings/mariadb-keyring.pgp
- Actualizar repositorio
apt update
- Instalación de servidor y cliente
apt install mariadb-client mariadb-server mariadb-plugin-provider-bzip2 mariadb-plugin-provider-lz4 mariadb-plugin-provider-lzma mariadb-plugin-provider-lzo mariadb-plugin-provider-snappy
- Inicializar base de datos
mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.
Enter current password for root (enter for none):
OK, successfully used password, moving on...
Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.
You already have your root account protected, so you can safely answer 'n'.
Switch to unix_socket authentication [Y/n] n
... skipping.
You already have your root account protected, so you can safely answer 'n'.
Change the root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] y
... Success!
Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] Y
... Success!
By default, MariaDB comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] Y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] Y
... Success!
Cleaning up...
All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!
Instalación PHP
Vamos a usar los repositorios PPA de ondrej/php
- Instalar repositorio PPA
add-apt-repository ppa:ondrej/php
- Actualizar repositorios
apt update
- Instalar PHP 8.5
apt install php8.5 php8.5-apcu php8.5-common php8.5-fpm php8.5-curl php8.5-gd php8.5-mysql php8.5-xml php8.5-xmlrpc php8.5-bz2 php8.5-imap php8.5-intl php8.5-mbstring php8.5-soap php8.5-gnupg php8.5-imagick php8.5-mcrypt php8.5-zip
Instalación Let's Encrypt
Vamos a usar Let's Encrypt para generar las claves y certificados usadas para comunicaciones HTTPS.
- Instalar Snap Core
snap install core
- Refrescar Snap Core
snap refresh core
- Instalar Certbot
snap install --classic certbot
- Crear enlace simbólico
ln -s /snap/bin/certbot /usr/local/bin/certbot
- Comprobar que está activada el timer de renovación
systemctl list-timers | grep certbot
Mon 2026-02-23 11:47:00 UTC 12h - - snap.certbot.renew.timer snap.certbot.renew.service
Configuración PHP
- Configuración php-fpm:
vi /etc/php/8.5/fpm/php.ini
[...]
; Maximum amount of memory a script may consume
; https://php.net/memory-limit
memory_limit = 128M
max_memory_limit = -1
[...]
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; https://php.net/post-max-size
post_max_size = 100M
[...]
; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting
; of zero causes PHP to behave as before. Default is 1. You should fix your scripts
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; https://php.net/cgi.fix-pathinfo
cgi.fix_pathinfo=0
[...]
; Whether to allow HTTP file uploads.
; https://php.net/file-uploads
file_uploads = On
[...]
; Maximum allowed size for uploaded files.
; https://php.net/upload-max-filesize
upload_max_filesize = 100M
[...]
; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20
[...]
[Session]
; Handler used to store/retrieve data.
; https://php.net/session.save-handler
session.save_handler = files
[...]
- Configuración php-cli:
vi /etc/php/8.5/cli/php.ini
[...]
; Maximum amount of memory a script may consume
; https://php.net/memory-limit
memory_limit = -1
max_memory_limit = -1
[...]
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; https://php.net/post-max-size
post_max_size = 100M
[...]
; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting
; of zero causes PHP to behave as before. Default is 1. You should fix your scripts
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; https://php.net/cgi.fix-pathinfo
cgi.fix_pathinfo=0
[...]
; Whether to allow HTTP file uploads.
; https://php.net/file-uploads
file_uploads = On
[...]
; Maximum allowed size for uploaded files.
; https://php.net/upload-max-filesize
upload_max_filesize = 100M
[...]
; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20
[...]
[Session]
; Handler used to store/retrieve data.
; https://php.net/session.save-handler
session.save_handler = files
[...]
- Reiniciar php-fpm:
systemctl restart php8.5-fpm.service
Configuración Nginx
- Backup nginx.conf
cp -a /etc/nginx/nginx.conf /etc/nginx/nginx.conf.$(date +%Y%m%d)
- Editar nginx.conf
vi /etc/nginx/nginx.conf
[...]
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
types_hash_max_size 2048;
client_max_body_size 100M;
server_tokens off;
[...]
##
# SSL Settings
##
#ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
[...]
}
- Generar PHParam:
mkdir /etc/nginx/ssl
openssl dhparam -out /etc/nginx/ssl/dhparam.pem 4096
- Configurar contraseñas:
Si se quiere configurar contraseñas Auth Basic se almacenan en /etc/nginx/passwd.
mkdir /etc/nginx/passwd
Por ejemplo:
htpasswd -c -B /etc/nginx/passwd/test.pw guzman
- Configurar snippets:
Estos "fragmentos" se pueden usar para permitir que sistemas funcionen si se tiene Auth Basic activo (como robots.txt o validación de Let's Encrypt).
vi /etc/nginx/snippets/allowed.conf
# Allow favicon.ico, robots.txt, .well-known/
location = /favicon.ico {
log_not_found off;
access_log off;
}
# Allow robots.txt
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# Allow "Well-Known URIs" as pwe RFC 5785 (e.g. Let's Encrypt)
location ~* ^/.well-known/ {
auth_basic off;
allow all;
}
vi /etc/nginx/snippets/denied.conf
# Deny *.txt, *.log, .*/*.php, .*, *.json, .lock, *.ht
# Not allow txt or logs to be downloaded
location ~* \.(txt|log)$ {
deny all;
}
# Not allow execute php in hidden folders
location ~ \..*/.\.php$ {
return 403;
}
# Not allow "hidden files"
location ~ (^|/)\. {
return 403;
}
# Not allow *.json or *.lock
location ~* \.(json|lock)$ {
return 403;
}
# Deny *.ht
location ~ /\.ht {
deny all;
}
vi /etc/nginx/snippets/hsts.conf
# Activate HSTS (HTTP Strict Transport Security)
# Note: if we set another header in a location we've to
# rewrite it
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
- Configurar sites-available:
En al carpeta /etc/nginx/sites-available/ se almacenan todos los Virtual Hosts disponibles. En Nginx hay que personalizar cada uno por cada tipo de aplicación. Hay que tener en cuenta las diferentes URL's.
- Configurar sites-enabled:
Se suelen configurar enlaces simbólicos con la carpeta sites-available para activarlos. Por ejemplo:
ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default
- Reiniciar Nginx:
systemctl restart nginx
Configuración MariaDB
- Conectar a MariaDB
mariadb
- Opción 1: Permitir conexiones por TCP (sólo desde localhost)
grant all privileges on *.* to 'root'@'localhost' identified by 'password' with grant option;
FLUSH PRIVILEGES;
- Opción 2: Permitir conexiones por Sockets UNIX (sólo desde localhost)
grant all privileges on *.* to 'root'@'localhost' identified via unix_socket with grant option;
FLUSH PRIVILEGES;
Nota: esta opción es la que suelo usar yo (no se pueden usar los dos a la vez).