Nginx

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Nginx and the translation is 15% complete.
Outdated translations are marked like this.


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.

Before immediately installing the www-servers/nginx package, first take a good look at the USE flags for Nginx.

Expanded USE flags

Nginx uses modules to enhance its features. To simplify the maintenance of this modular approach, the nginx ebuild uses expanded USE (USE_EXPAND) flags to denote which modules should be installed.

  • HTTP related modules can be enabled through the NGINX_MODULES_HTTP variable
  • Mail related modules can be enabled through the NGINX_MODULES_MAIL variable
  • Third party modules can be enabled through the NGINX_ADD_MODULES variable

These variables need to be set in /etc/portage/make.conf. Their descriptions can be found in /var/db/repos/gentoo/profiles/desc/nginx_modules_http.desc and /var/db/repos/gentoo/profiles/desc/nginx_modules_mail.desc.

For example, to enable the fastcgi module:

ARCHIVO /etc/portage/make.conf
NGINX_MODULES_HTTP="fastcgi"

The above will overwrite the default value of NGINX_MODULES_HTTP and set it to fastcgi. To enable the fastcgi module without overwriting the default NGINX_MODULES_HTTP value, the following USE flag notation can be specified in /etc/portage/package.use:

ARCHIVO /etc/portage/package.use
www-servers/nginx NGINX_MODULES_HTTP: fastcgi

Ajustes USE

USE flags for www-servers/nginx Robust, small and high performance http and reverse proxy server

aio Enables file AIO support
debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
http Enable HTTP core support
http-cache Enable HTTP cache support
http2 Enable HTTP2 module support
http3 Enable HTTP3 module support
ktls Enable Kernel TLS offload (kTLS)
libatomic Use libatomic instead of builtin atomic operations
pcre Add support for Perl Compatible Regular Expressions
pcre-jit Enable JIT for pcre
pcre2 Enable support for pcre2
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.
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

With the USE flags set, install www-servers/nginx:

root #emerge --ask www-servers/nginx

Installation verification

The default nginx configuration defines a virtual server with the root directory set to /var/www/localhost/htdocs. However due to bug #449136, the nginx ebuild will only create the /var/www/localhost directory and without an index file. To have a working default configuration, create the /var/www/localhost/htdocs directory and simple index file:

root #mkdir /var/www/localhost/htdocs
root #echo '¡Hola mundo!' > /var/www/localhost/htdocs/index.html

The nginx package installs an init service script allowing administrators to stop, start, or restart the service. Run the next command to start the nginx service:

root #/etc/init.d/nginx start

To verify that nginx is properly running, point a web browser to the http://localhost address or use a command-line web tool like curl:

user $curl http://localhost

Configuration

The nginx configuration is handled through the /etc/nginx/nginx.conf file.

Single site access

The following example shows a single-site access, without dynamic capabilities (such as PHP).

ARCHIVO /etc/nginx/nginx.confConfiguración por defecto de Gentoo
user 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;
	}
}

Multiple site access

It is possible to leverage the include directive to split the configuration in multiple files:

ARCHIVO /etc/nginx/nginx.confConfiguración Multisitio
user 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;
}
ARCHIVO /etc/nginx/conf.d/local.confSencillo servidor
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;
}
ARCHIVO /etc/nginx/conf.d/local-ssl.confSencillo servidor SSL
server {
    listen 443 ssl;
    server_name host.tld;
    ssl_certificate /etc/ssl/nginx/host.tld.pem;
    ssl_certificate_key /etc/ssl/nginx/host.tld.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:AES128:AES256:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK;
    ssl_dhparam /etc/ssl/nginx/host.tld.dh4096.pem;
    ssl_session_timeout 5m;
    ssl_session_cache shared:SSL:50m;
}

PHP support

Add the following lines to the nginx configuration to enable PHP support. In this example nginx is exchanging information with the PHP process via a UNIX socket.

ARCHIVO /etc/nginx/nginx.confHabilitar soporte PHP
...
http {
...
    server { 
    ...
            location ~ \.php$ {
                       # Comprobar que hay guiones no existentes o lanzar un error 404r
                       # Sin esta línea nginx enviará cualquier petición que acabe en .php a php-fpm
                       try_files $uri =404;
                       include /etc/nginx/fastcgi.conf;
                       fastcgi_pass unix:/run/php-fpm.socket;
           }
    }
}

To support this setup, PHP needs to be built with FastCGI Process Manager support (dev-lang/php), which is handled through the fpm USE flag:

root #echo "dev-lang/php fpm" >> /etc/portage/package.use

Rebuild PHP with the fpm USE flag enabled:

root #emerge --ask dev-lang/php
Nota
Using UNIX socket communication is the preferred and recommended configuration

For PHP 7.0 and newer PHP versions use following configuration:

ARCHIVO /etc/php/fpm-php7.1/fpm.d/www.confRunning PHP with UNIX socket support
listen = /run/php-fpm.socket
listen.owner = nginx

Set the timezone in the php-fpm php.ini file. Substitute the <PUT_TIMEZONE_HERE> text in the FileBox below with the appropriate timezone information:

ARCHIVO /etc/php/fpm-php5.5/php.iniConfigurar la zona horaria en php.ini
date.timezone = <PONER_LA_ZONA_HORARIA_AQUÍ>

Start the php-fpm daemon:

root #/etc/init.d/php-fpm start

Add php-fpm to the default runlevel:

root #rc-update add php-fpm default

Reload nginx with changed configuration:

root #/etc/init.d/nginx reload

Alternatively, for systemd:

root #systemctl enable php-fpm@7.1
root #systemctl start php-fpm@7.1

IP address access list

The next example shows how to allow access to a particular URL (in this case /nginx_status) only to:

  • certain hosts (e.g. 192.0.2.1 127.0.0.1)
  • and IP networks (e.g. 198.51.100.0/24)
ARCHIVO /etc/nginx/nginx.confHabilitar y configurar las listas de acceso por IP para la página /nginx_status
http {
    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;
             }
     }
}

Basic authentication

nginx allows limiting access to resources by validating the user name and password:

ARCHIVO /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;
             }
     }
}

Se puede generar el fichero htpasswd mediante:

The htpasswd file can be generated using:

user $openssl passwd

Geolocation using GeoIP2

The GeoIP2 module makes use of GeoIP2 databases by Maxmind or similar. Using Maxmind is already supported in Gentoo through net-misc/geoipupdate. However, registration of an account is required in order to obtain a free license key and download the free database.

Downloading Maxmind GeoIP2 databases

Once an account is created, install and configure geoipupdate:

root #emerge --ask net-misc/geoipupdate

Enter the account and license key:

ARCHIVO /etc/GeoIP.confAdd your account info
AccountID YOURID
LicenseKey YOURKEY
EditionIDs GeoLite2-ASN GeoLite2-City GeoLite2-Country

After that, you'll need to download the databases:

root #geoipupdate

In order receive updates automatically in the future, add this command to a weekly cronjob or systemd timer.

Add GeoIP2 support to Nginx

To enable to modules and rebuild Nginx:

ARCHIVO /etc/portage/package.use/nginxAdd the modules to Nginx
www-servers/nginx NGINX_MODULES_HTTP: geo geoip2
Nota
The geoip module only supports the GeoIP legacy database.

Rebuild nginx with the third party modules enabled:

root #emerge --ask www-servers/nginx

Once Nginx has been rebuild, point Nginx to the databases and the GeoIP2 variables:

ARCHIVO /etc/nginx/nginx.confPointing to the GeoIP2 databases and its values
http {
...
    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;
    }
...
}

The auto_reload option will allow updating the database without restarting Nginx.

For the GeoIP2 values to show up in a PHP application, assign them as fastcgi_param values:

ARCHIVO /etc/nginx/fastcgi.confAdd GeoIP2 support to 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;

Third party modules

Download third party module source and move it to /usr/src. Manually compile the selected Nginx module, then add the following line to /etc/portage/make.conf:

ARCHIVO /etc/portage/make.confAdding third party module
NGINX_ADD_MODULES="/usr/src/nginxmodule"

Rebuild nginx with the third party module enabled:

root #emerge --ask www-servers/nginx

Usage

Service control

OpenRC

Start nginx web server:

root #/etc/init.d/nginx start

Stop nginx web server:

root #/etc/init.d/nginx stop

Add nginx to the default runlevel so that the service starts automatically on system reboot:

root #rc-update add nginx default

Reload nginx configuration without dropping connections:

root #rc-service nginx reload

Reiniciar el servicio nginx:

root #/etc/init.d/nginx restart

systemd

Start nginx web server:

root #systemctl start nginx

Stop nginx web server:

root #systemctl stop nginx

Check the status of the service:

root #systemctl status nginx

Enable service to start automatically on system reboot:

root #systemctl enable nginx

Reload nginx configuration without dropping connections:

root #systemctl reload nginx

Restart the nginx service:

root #systemctl restart nginx

Resolución de problemas

In case of problems, the following commands can help troubleshoot the situation.

Validate configuration

Verify that the running nginx configuration has no errors:

root #/usr/sbin/nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

By running nginx with the -t option, it will validate the configuration file without actually starting the nginx daemon. Use the -c option with the full path to the file to test configuration files in non-default locations.

Verify processes are running

Check if nginx processes are running:

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

Verify bound addresses and ports

Verify nginx daemon is listening on the right TCP port (such as 80 for HTTP or 443 for HTTPS):

root #netstat -tulpen | grep :80
tcp        0      0 127.0.0.1:80            0.0.0.0:*               LISTEN      0          12336835   -26092/nginx: master

Ver también

Recursos externos