Nginx
nginx es un pequeño y robusto servidor web de alto rendimiento que puede actuar también como servidor proxy reverso. Es una buena alternativa a servidores populares como Apache y lighttpd.
Instalación
Antes de instalar el paquete www-servers/nginx , primero revise bien los ajustes USE para nginx.
Expansión de los ajustes USE
Nginx usa módulos para mejorar sus características. Con el propósito de simplificar el mantenimiento de esta aproximación modular, la ebuild de nginx usa ajustes USE expandidos (USE_EXPAND ) a fin de establecer que módulos deben ser instalados.
- Módulos referentes a HTTP son activados a través de la variable NGINX_MODULES_HTTP
- Módulos referentes al Email son activados a través de la variable NGINX_MODULES_MAIL
- Módulos de terceros son activados a través de la variable NGINX_ADD_MODULES
Estas variables pueden ser establecidas en /etc/portage/make.conf. Sus descripciónes se encuentran en /var/db/repos/gentoo/profiles/desc/nginx_modules_http.desc y /var/db/repos/gentoo/profiles/desc/nginx_modules_mail.desc .
Por ejemplo, para activar el módulo fastcgi:
/etc/portage/package.usewww-servers/nginxNGINX_MODULES_HTTP:fastcgi
Ajustes USE
USE flags for www-servers/nginx Robust, small and high performance HTTP and reverse proxy server
+http
Enable core HTTP support
+http-cache
Enable HTTP cache support
+http2
Enable HTTP2 module support
+modules
Enable loadable module support
+pcre2
Enable support for pcre2
aio
Enable asynchronous I/O support
debug
Enable support for debugging log
http3
Enable HTTP3 module support
ktls
Enable Kernel TLS offload (kTLS)
libatomic
Use dev-libs/libatomic_ops instead of builtin atomic operations
mail
Enable POP3/IMAP4/SMTP mail proxy server
pcre
Add support for Perl Compatible Regular Expressions
pcre-jit
Enable JIT for pcre
rtmp
NGINX-based Media Streaming Server
selinux
!!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
ssl
Enable HTTPS module for http. Enable SSL/TLS support for POP3/IMAP/SMTP for mail.
stream
Enable generic TCP/UDP proxying and load balancing
test
Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
threads
Add threads support for various packages. Usually pthreads
vim-syntax
Pulls in related vim syntax scripts
Emerge
Con los ajustes USE establecidos, puede instalar www-servers/nginx :
root #emerge --ask www-servers/nginxVerificación de la instalación
La configuración por defecto de Nginx establece un servidor virtual con la raiz en /var/www/localhost/htdocs. Sin embargo debido al bug #449136 , la ebuild de Nginx solamente va a crear el fichero /var/www/localhost sin el archivo índice. Para hacer funcionar la configuración predeterminada, cree el directorio /var/www/localhost/htdocs y un archivo índice simple:
root #mkdir -p /var/www/localhost/htdocsThen, uncomment the root directive inside the server block:
/etc/nginx/nginx.confSetting the root directiveserver{ listen127.0.0.1; server_namelocalhost; # Substitute the directory below for the one you use. root/var/www/localhost/htdocs; }
You can copy a sample welcome page to the root directory. For example, if /var/www/localhost/htdocs was chosen, use the following command to copy the welcome page to the root:
root #cp /usr/share/nginx/index.html /var/www/localhost/htdocsEl paquete de Nginx instala e inicializa la rutina del servicio, permitiendo a les administradores parar, iniciar o reiniciar el servicio. Corra el siguiente comando para iniciar el servicio Nginx:
root #/etc/init.d/nginx startIf using systemd, use the following command to start NGINX:
root #systemctl start nginx.servicePara verificar que Nginx esta corriendo correctamente, apunte un explorador web a la dirección http://localhost o use una heramienta web de línea de comandos como curl:
user $curl http://localhostConfiguración
La configuración de Nginx es manejada a través del archivo /etc/nginx/nginx.conf.
Acceso a un solo sitio
El siguiente ejemplo muestra el acceso a un solo sitio web, sin capacidades dinámicas (como PHP).
/etc/nginx/nginx.confConfiguración por defecto de Gentoouser nginx nginx;
worker_processes 1;
error_log /var/log/nginx/error_log info;
events {
worker_connections 1024;
use epoll;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main
'$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
client_header_timeout 10m;
client_body_timeout 10m;
send_timeout 10m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 4 2k;
request_pool_size 4k;
gzip off;
output_buffers 1 32k;
postpone_output 1460;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 75 20;
ignore_invalid_headers on;
index index.html;
server {
listen 127.0.0.1;
server_name localhost;
access_log /var/log/nginx/localhost.access_log main;
error_log /var/log/nginx/localhost.error_log info;
root /var/www/localhost/htdocs;
}
}
Acceso a múltiples sitios
Es posible aprovechar la directriz include "incluir" para repartir la configuración en múltiples archivos:
/etc/nginx/nginx.confConfiguración multisitiouser nginx nginx;
worker_processes 1;
error_log /var/log/nginx/error_log info;
events {
worker_connections 1024;
use epoll;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main
'$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
client_header_timeout 10m;
client_body_timeout 10m;
send_timeout 10m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 4 2k;
request_pool_size 4k;
gzip off;
output_buffers 1 32k;
postpone_output 1460;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 75 20;
ignore_invalid_headers on;
index index.html;
include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/local.confAnfitrion simpleserver {
listen 127.0.0.1;
server_name localhost;
access_log /var/log/nginx/localhost.access_log main;
error_log /var/log/nginx/localhost.error_log info;
root /var/www/localhost/htdocs;
}
/etc/nginx/conf.d/local-ssl.confAnfitrion SSL simpleserver {
listen 443 ssl;
server_name host.tld;
ssl_certificate /etc/ssl/nginx/host.tld.pem;
ssl_certificate_key /etc/ssl/nginx/host.tld.key;
}
Soporte de PHP
Añada las siguientes líneas a la configuración de Nginx para habilitar el soporte de PHP. En este ejemplo Nginx se comunica con el proceso de PHP via puerto UNIX.
/etc/nginx/nginx.confHabilitar soporte de PHP...
http {
...
server {
...
location ~ \.php$ {
# Probar rutinas no existentes arroja el error 404
# Sin esta línea, Nginx va a enviar ciegamente cualquier petición que termine en.php a php-fpm
try_files $uri =404;
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/run/php-fpm.socket;
}
}
}
Para habilitar esta configuración, PHP necesita ser compilado con el Soporte de Administrador de Procesos FastCGI (dev-lang/php ), el cual es invocado con el ajuste USE fpm:
root #echo "dev-lang/php fpm" >> /etc/portage/package.useReconstruya PHP activando el ajuste USE fpm:
root #emerge --ask dev-lang/phpLa comunicación mediante un puerto UNIX es la configuración recomendada
Para PHP 7.0 Y nuevas versiones de PHP, use la siguiente configuración:
/etc/php/fpm-php7.1/fpm.d/www.confCorrer PHP con soporte puerto UNIXlisten=/run/php-fpm.socket listen.owner=nginx
Establezca la zona horaria en el archivo de php-fpm php.ini. Sustituya el texto <PONER_LA_ZONA_HORARIA_AQUÍ> en la caja de archivos de abajo con la zona horaria apropiada:
/etc/php/fpm-php5.5/php.iniConfigurar la zona horaria en php.inidate.timezone=<PONER_LA_ZONA_HORARIA_AQUÍ>
Inicialice el demonio php-fpm:
root #/etc/init.d/php-fpm startAñada php-fpm al nivel de ejecución por defecto:
root #rc-update add php-fpm defaultVuelva a cargar nginx con la nueva configuración:
root #/etc/init.d/nginx reloadAlternativamente, para systemd:
root #systemctl enable php-fpm@7.1
root #systemctl start php-fpm@7.1root #systemctl enable php-fpm@8.2
root #systemctl start php-fpm@8.2
root #systemctl restart nginx.serviceLista de acceso a direcciones IP
El siguiente ejemplo expone como acceder a una URL particular (en este caso solo a /nginx_status):
- ciertos anfitriones (p.ej. 192.0.2.1 127.0.0.1)
- y direcciónes IP (p.ej. 198.51.100.0/24)
/etc/nginx/nginx.confHabilitar y configurar las listas de acceso por IP para la página /nginx_statushttp {
server {
location /nginx_status {
stub_status on;
allow 127.0.0.1/32;
allow 192.0.2.1/32;
allow 198.51.100.0/24;
deny all;
}
}
}
Autenticación básica
Nginx permite limitar el acceso a los recursos validando el nombre de usuario y la contraseña:
/etc/nginx/nginx.confHabilitar y configurar la autenticación de usuarios para la localización /http {
server {
location / {
auth_basic "Authentication failed";
auth_basic_user_file conf/htpasswd;
}
}
}
El archivo htpasswd puede ser creado usando:
user $openssl passwdThis will create the domain.htpasswd file, containing a row for the user 'foo'.
The string with the user name should end with ':', this is the separator field between the user name and the password.
user $openssl passwd >> domain.htpasswdThis will add the password to the line for the user 'foo'. The password will be asked on the standard input. Once it's over, the file could be opened and will contain something like this:
/etc/nginx/domain.htpasswdContent of the domain.htpasswd file, for user foo with a ciphered passwordfoo:1ドル$lpC3de5Y$dnh6jegS1qlfZVo7rGExz/
The password is not in plain text, rather it is encrypted with OpenSSL.
Geolocación usando GeoIP2
El módulo GeoIP2 hace uso de las bases de datos GeoIP2 de Maxmind o similares. El uso de Maxmind ya es compatible con Gentoo usando net-misc/geoipupdate . Sin embargo, es necesario registrar una cuenta a fin de obtener y descargar una clave licenciada y base de datos gratuitas.
Descargar bases de datos Maxmind GeoIP2
Una vez la cuenta es creada, instale y configure geoipupdate:
root #emerge --ask net-misc/geoipupdateIngrese la cuenta y clave de licencia:
/etc/GeoIP.confAñada su información de cuentaAccountID YOURID LicenseKey YOURKEY EditionIDs GeoLite2-ASN GeoLite2-City GeoLite2-Country
Luego, se deben descargar las bases de datos:
root #geoipupdate
Para recibir futuras actualizaciones automáticamente, agregue este comando a un cronjob semanal o temporizador systemd.
Añada el soporte de GeoIP2 en Nginx
Para habilitar módulos y reconstruir Nginx:
/etc/portage/package.use/nginxAñada los módulos a Nginxwww-servers/nginx NGINX_MODULES_HTTP: geo geoip2
El módulo geoip solamente soporta la base de datos clasica de GeoIP.
Reconstruya nginx con los módulos de terceros habilitados:
root #emerge --ask www-servers/nginxUna vez Nginx ha sido recompilado, apuntelo a las bases de datos y variables de GeoIP2:
/etc/nginx/nginx.confApuntar a las bses de datos y valores de GeoIP2http {
...
geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
auto_reload 5m;
$geoip2_metadata_city_build metadata build_epoch;
$geoip2_data_city_name city names en;
$geoip2_data_city_geonameid city geoname_id;
$geoip2_data_continent_code continent code;
$geoip2_data_continent_geonameid continent geoname_id;
$geoip2_data_continent_name continent names en;
$geoip2_data_country_geonameid country geoname_id;
$geoip2_data_country_code iso_code;
$geoip2_data_country_name names en;
$geoip2_data_country_is_eu is_in_european_union;
$geoip2_data_location_accuracyradius location accuracy_radius;
$geoip2_data_location_latitude location latitude;
$geoip2_data_location_longitude location longitude;
$geoip2_data_location_metrocode location metro_code;
$geoip2_data_location_timezone location time_zone;
$geoip2_data_postal_code postal code;
$geoip2_data_rcountry_geonameid registered_country geoname_id;
$geoip2_data_rcountry_iso registered_country iso_code;
$geoip2_data_rcountry_name registered_country names en;
$geoip2_data_rcountry_is_eu registered_country is_in_european_union;
$geoip2_data_region_geonameid subdivisions 0 geoname_id;
$geoip2_data_region_iso subdivisions 0 iso_code;
$geoip2_data_region_name subdivisions 0 names en;
}
geoip2 /usr/share/GeoIP/GeoLite2-ASN.mmdb {
auto_reload 5m;
$geoip2_data_autonomous_system_number autonomous_system_number;
$geoip2_data_autonomous_system_organization autonomous_system_organization;
}
...
}
La opción auto_reload permitirá actualizar la base de datos sin reiniciar Nginx.
Para que los valores de GeoIP2 aparezcan en la aplicación PHP, asígnelos como valores de fastcgi_param:
/etc/nginx/fastcgi.confAgregue soporte de GeoIP2 a PHP... fastcgi_param GEOIP2_CITY_BUILD_DATE $geoip2_metadata_city_build; fastcgi_param GEOIP2_CITY $geoip2_data_city_name; fastcgi_param GEOIP2_CITY_GEONAMEID $geoip2_data_city_geonameid; fastcgi_param GEOIP2_CONTINENT_CODE $geoip2_data_continent_code; fastcgi_param GEOIP2_CONTINENT_GEONAMEID $geoip2_data_continent_geonameid; fastcgi_param GEOIP2_CONTINENT_NAME $geoip2_data_continent_name; fastcgi_param GEOIP2_COUNTRY_GEONAMEID $geoip2_data_country_geonameid; fastcgi_param GEOIP2_COUNTRY_CODE $geoip2_data_country_code; fastcgi_param GEOIP2_COUNTRY_NAME $geoip2_data_country_name; fastcgi_param GEOIP2_COUNTRY_IN_EU $geoip2_data_country_is_eu; fastcgi_param GEOIP2_LOCATION_ACCURACY_RADIUS $geoip2_data_location_accuracyradius; fastcgi_param GEOIP2_LATITUDE $geoip2_data_location_latitude; fastcgi_param GEOIP2_LONGITUDE $geoip2_data_location_longitude; fastcgi_param GEOIP2_LOCATION_METROCODE $geoip2_data_location_metrocode; fastcgi_param GEOIP2_LOCATION_TIMEZONE $geoip2_data_location_timezone; fastcgi_param GEOIP2_POSTAL_CODE $geoip2_data_postal_code; fastcgi_param GEOIP2_REGISTERED_COUNTRY_GEONAMEID $geoip2_data_rcountry_geonameid; fastcgi_param GEOIP2_REGISTERED_COUNTRY_ISO $geoip2_data_rcountry_iso; fastcgi_param GEOIP2_REGISTERED_COUNTRY_NAME $geoip2_data_rcountry_name; fastcgi_param GEOIP2_REGISTERED_COUNTRY_IN_EU $geoip2_data_rcountry_is_eu; fastcgi_param GEOIP2_REGION_GEONAMEID $geoip2_data_region_geonameid; fastcgi_param GEOIP2_REGION $geoip2_data_region_iso; fastcgi_param GEOIP2_REGION_NAME $geoip2_data_region_name; fastcgi_param GEOIP2_ASN $geoip2_data_autonomous_system_number; fastcgi_param GEOIP2_ASN_ORG $geoip2_data_autonomous_system_organization;
Uso
Control del servicio
OpenRC
Iniciar el servidor web Nginx:
root #rc-service nginx startParar el servidor web Nginx:
root #rc-service nginx stopAgregue Nginx al nivel de ejecución predeterminado para que el servicio inicie automáticamente al reiniciar el sistema:
root #rc-update add nginx defaultRecargar la configuración de nginx sin perder conexiones:
root #rc-service nginx reloadReiniciar el servicio nginx:
root #rc-service nginx restartsystemd
Iniciar el servidor web Nginx:
root #systemctl start nginxParar el servidor web Nginx:
root #systemctl stop nginxVerificar el estado del servicio:
root #systemctl status nginxHabilitar el servicio para que inicie automáticamente al reiniciar el sistema:
root #systemctl enable nginxRecargar la configuración de nginx sin perder conexiones:
root #systemctl reload nginxReiniciar el servicio Nginx:
root #systemctl restart nginxResolución de problemas
Al encontrar inconvenientes, los siguientes comandos pueden ayudar a solucionar la situación.
Validar configuración
Verifique que la configuración de nginx en ejecución no tenga errores:
root #rc-service nginx configtestnginx | * Checking NGINX's configuration ... nginx |nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx |nginx: configuration file /etc/nginx/nginx.conf test is successful [ ok ]
Alternatively, if using systemd:
root #/usr/sbin/nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Al ejecutar nginx con la opción -t, se validará el archivo de configuración sin realmente iniciar el demonio nginx. Utilice la opción -c con la ruta completa al archivo para probar los archivos de configuración en ubicaciones que no sean las predeterminadas.
Verificar que los procesos esten corriendo
Compruebe si los procesos nginx se están ejecutando:
user $ps aux | egrep 'nginx|PID'PID TTY STAT TIME COMMAND 26092 ? Ss 0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf 26093 ? S 0:00 nginx: worker proces
Verificar las direcciones y puertos de enlace
Verifique que el demonio nginx esté escuchando en el puerto TCP correcto (como 80 para HTTP o 443 para HTTPS):
root #ss -tulpn | grep :80tcp LISTEN 0 0 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=6253,fd=52),("nginx",pid=6252,fd=52))
Ver también
- Apache — un servidor Web eficiente y extensible. Es uno de los servidores Web más populares usados en Internet.
- Lighttpd — a fast and lightweight web server.
Recursos externos
- https://nginx.org/en/docs/beginners_guide.html - Una guía de nginx para principiantes. De ayuda para quéllos que apenas conocen nginx.
- https://nginx.com/resources/admin-guide/ - La guía de administración de ngnix. Ayuda para administradores web que trabajan en este área.
- http://wiki.nginx.org/Main - El wiki de nginx.
- https://github.com/h5bp/server-configs-nginx - Configuración H5BP de nginx.