Nginx
nginx ist ein robuster, kleiner und hochperformanter Web-Server und ein Reverse-Proxy-Server. Er ist eine gute Alternative zu populären Webservern wie Apache und lighttpd.
Installation
Vor der unmittelbaren Installation des www-servers/nginx Paketes, ist es sinnvoll die USE-Flags für Nginx zu betrachten.
Erweiterte USE-Flags
Nginx nutzt Module um seine Funktionalitäten zu erweitern. Um die Verwaltung dieses modularen Aufbaus zu vereinfachen, nutzt der nginx-ebuild erweiterte USE (USE_EXPAND ) -Flags um anzuzeigen welche Module installiert werden sollen.
- HTTP-bezogene Module können durch die NGINX_MODULES_HTTP -Variable aktiviert werden
- Mail-bezogene Module können durch die NGINX_MODULES_MAIL -Variable aktiviert werden
- Drittparteien-Module können durch die NGINX_ADD_MODULES -Variable aktiviert werden
Diese Variablen müssen in /etc/portage.make.conf gesetzt werden. Ihre Beschreibung kann unter /var/db/repos/gentoo/profiles/desc/nginx_modules_http.desc und /var/db/repos/gentoo/profiles/desc/nginx_modules_mail.desc gefunden werden.
Um zum Beispiel das fastcgi Modul zu aktivieren :
/etc/portage/package.usewww-servers/nginxNGINX_MODULES_HTTP:fastcgi
USE-Flags
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
Mit gesetzten USE-Flags, www-servers/nginx installieren :
root #emerge --ask www-servers/nginxInstallationsverifizierung
Die Standardkonfiguration von nginx definiert einen virtuellen Server mit dem Wurzelverzeichnis gesetzt auf /var/www/localhost/htdocs. Aufgrund des bug #449136 erstellt das nginx-ebuild nur das Verzeichnis /var/www/localhost und ohne eine Indexdatei. Um eine funktionierende Standardkonfiguration zu erhalten, das Verzeichnis /var/www/localhost/htdocs und eine simple Indexdatei erstellen:
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/htdocsDas nginx-Paket installiert einen Init-Dienst welcher Administratoren erlaubt, ihn zu stoppen, zu starten oder neuzustarten. Das nächste Kommando ausführen um den nginx-Dienst zu starten:
root #/etc/init.d/nginx startIf using systemd, use the following command to start NGINX:
root #systemctl start nginx.serviceUm sicherzustellen, dass nginx korrekt läuft, mit einem Webbrowser die Adresse [http://localhost] aufrufen oder ein Kommandozeilentool wie curl benutzen:
user $curl http://localhostKonfiguration
Die Nginx-Konfiguration wird mittels der /etc/nginx/nginx.conf-Datei gesteuert.
Einzelseiten-Zugriff
Das folgende Beispiel zeigt einen Einzelseiten-Zugang, ohne dynamische Möglichkeiten (wie z.B. PHP).
/etc/nginx/nginx.confGentoo's Standard-Konfigurationuser 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;
}
}
Multiseiten-Zugriff
Es ist möglich die include -Direktive auszuhebeln um die Konfiguration in mehrere Teile aufzuspalten :
/etc/nginx/nginx.confMultiseiten-Konfigurationuser 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.confSimpler Hostserver {
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.confEinfacher SSL-Hostserver {
listen 443 ssl;
server_name host.tld;
ssl_certificate /etc/ssl/nginx/host.tld.pem;
ssl_certificate_key /etc/ssl/nginx/host.tld.key;
}
PHP-Unterstützung
Die folgenden Seiten zur nginx-Konfiguration hinzufügen um PHP-Unterstützung zu aktivieren. In diesem Beispiel tauscht nginx Informationen mit dem PHP-Prozess über einen UNIX-Socket aus.
/etc/nginx/nginx.confPHP-Unterstützung aktivieren...
http {
...
server {
...
location ~ \.php$ {
# Nach nicht existenten Skripten suchen oder einen 404-Fehler zurückgeben
# Ohne diese Zeile sendet nginx blind jede Anfrage, die auf .php endet, zu php-fpm
try_files $uri =404;
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/run/php-fpm.socket;
}
}
}
Um dieses Setup zu unterstützen, muss PHP mit Unterstützung für den FastCGI Prozess-Manager dev-lang/php gebaut werden, was durch die fpm USE-Flag gesteuert wird:
root #echo "dev-lang/php fpm" >> /etc/portage/package.usePHP mit der aktivierten fpm USE-Flag neu bauen:
root #emerge --ask dev-lang/phpUNIX-Socket-Kommunikation zu nutzen ist die präferierte und empfohlene Konfiguration
Using UNIX socket communication is the preferred and recommended configuration
Für PHP 7.0 und neuere PHP-Versionen verwenden Sie folgende Konfiguration:
/etc/php/fpm-php7.1/fpm.d/www.confPHP mit UNIX-Socket-Unterstützung ausführenlisten=/run/php-fpm.socket listen.owner=nginx
Die Zeitzone in der php-fpm-Datei php.ini setzen. Den <PUT_TIMEZONE_HERE>-Text in der FileBox hierunter mit der passenden Zeitzoneninformation ersetzen.
/etc/php/fpm-php5.5/php.iniZeitzone in php.ini einstellendate.timezone=<PUT_TIMEZONE_HERE>
Den php-fpm-Daemon starten:
root #/etc/init.d/php-fpm startphp-fpm zum Default-Runlevel hinzufügen:
root #rc-update add php-fpm defaultnginx mit geänderter Konfiguration neu laden:
root #/etc/init.d/nginx reloadAlternativ für 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.serviceIP-Adressen-Zugriffsliste
Das nächste Beispiel zeigt wie man den Zugriff zu einer bestimmten URL (in diesem Fall /nginx_status) nur folgendem erlaubt:
- bestimmten Hosts (z.B. "192.0.2.1 127.0.0.1")
- und bestimmten IP-Netzwerken (z.B. "198.51.100.0/24")
/etc/nginx/nginx.confAktivieren und Konfigurieren einer IP-Zugriffsliste für die /nginx_status Seitehttp {
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;
}
}
}
Grundlegende Authentifizierung
nginx erlaubt es, den Zugriff durch Validieren des Benutzernamens und Passwortes einzuschränken:
/etc/nginx/nginx.confAktivieren und Konfigurieren der Benutzerauthentifizierung für das / Verzeichnishttp {
server {
location / {
auth_basic "Authentication failed";
auth_basic_user_file conf/htpasswd;
}
}
}
Die htpasswd-Datei kann erzeugt werden mittels:
The domain.htpasswd file can be generated using:
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.
Geolokalisierung mit GeoIP2
Das GeoIP2-Modul nutzt die GeoIP2-Datenbanken von Maxmind oder ähnlichen. Die Verwendung von Maxmind wird in Gentoo bereits durch net-misc/geoipupdate unterstützt. Allerdings ist die Registrierung eines Kontos erforderlich, um einen kostenlosen Lizenzschlüssel zu erhalten und die kostenlose Datenbank herunterzuladen.
Herunterladen von Maxmind GeoIP2-Datenbanken
Sobald Sie ein Konto erstellt haben, installieren und konfigurieren Sie geoipupdate:
root #emerge --ask net-misc/geoipupdateGeben Sie das Konto und den Lizenzschlüssel ein:
/etc/GeoIP.confFügen Sie Ihre Kontoinformationen hinzuAccountID YOURID LicenseKey YOURKEY EditionIDs GeoLite2-ASN GeoLite2-City GeoLite2-Country
Danach müssen Sie die Datenbank herunterladen:
root #geoipupdate
Um in Zukunf automatisch Updates zu erhalten, fügen Sie diesen Befehl zu einem wöchtenlichen Cronjob oder systemd-Timer hinzu.
Hinzufügen von GeoIP2-Unterstützung zu Nginx
Um Module zu aktivieren und Nginx neu zu erstellen:
/etc/portage/package.use/nginxHinzufügen der Module zu Nginxwww-servers/nginx NGINX_MODULES_HTTP: geo geoip2
Das geoip-Modul unterstützt nur die GeoIP-Legacy-Datenbank.
Erstellen Sie Nginx neu, wobei die Module von Drittanbietern aktiviert werden:
root #emerge --ask www-servers/nginxSobald Nginx neu erstellt wurde, verweisen Sie Nginx auf die Datenbanken und die GeoIP2-Variablen:
/etc/nginx/nginx.confVerweis auf die GeoIP2-Datenbanken und ihre Wertehttp {
...
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;
}
...
}
Die Option auto_reload ermöglicht die Aktualisierung der Datenbank ohne Neustart von Nginx.
Damit die GeoIP2-Werte in einer PHP-Anwendung angezeigt werden, müssen sie als fastcgi_param-Werte zugewiesen werden:
/etc/nginx/fastcgi.confHinzufügen von GeoIP2-Unterstützung zu 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;
Bedienung
Service-Kontrolle
OpenRC
nginx-Webserver starten:
root #rc-service nginx startnginx-Webserver stoppen:
root #rc-service nginx stopFügen Sie nginx zum Standard-Runlevel hinzu, damit der Dienst beim Neustart des Systems automatisch startet:
root #rc-update add nginx defaultLaden Sie die nginx-Konfiguration neu, ohne die Verbindungen zu unterbrechen:
root #rc-service nginx reloadDen nginx-Service neustarten:
root #rc-service nginx restartsystemd
nginx-Webserver starten:
root #systemctl start nginxnginx-Webserver stoppen:
root #systemctl stop nginxÜberprüfen Sie den Status des Dienstes:
root #systemctl status nginxAktivieren Sie den Dienst, damit er beim Neustart des Systems automatisch gestartet wird:
root #systemctl enable nginxLaden Sie die nginx-Konfiguration neu, ohne die Verbindungen zu unterbrechen:
root #systemctl reload nginxStarten Sie den nginx-Dienst neu:
root #systemctl restart nginxFehlersuche
Im Falle eines Problems können die folgenden Kommandos bei der Fehlersuche helfen.
Validierung der Konfiguration
Verifizieren dass die laufende nginx-Konfiguration keine Fehler aufweist:
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
Beim Ausführen von nginx mit der -t Option wird die Konfigurationsdatei validiert ohne den nginx-Daemon zu starten. Verwenden Sie die Option -c mit dem vollständigen Dateipfad, um Konfigurationsdateien zu testen, die sich nicht an den Standardspeicherorten befinden.
Verifizieren dass Prozesse laufen
Prüfen dass die nginx-Prozesse laufen:
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
Gebundene Adressen und Ports verifizieren
Verifizieren dass der nginx-Daemon auf dem richtigen TCP-Port lauscht (wie zum Beispiel 80 für HTTP oder 443 für HTTPS):
root #netstat -tulpen | grep :80tcp 0 0 127.0.0.1:80 0.0.0.0:* LISTEN 0 12336835 -26092/nginx: master
Siehe auch
- Apache — ein effizienter und erweiterbarer Web-Server. Es ist einer der am häufigsten eingesetzten Web-Server im Internet.
- Lighttpd — a fast and lightweight web server.
Externe Ressourcen
- https://nginx.org/en/docs/beginners_guide.html - Eine nginx Anfänger-Anleitung. Hilfreich für diejenigen die nicht viel über nginx wissen.
- https://nginx.com/resources/admin-guide/ - Die ngnix Administrations-Anleitung. Hilfreich für Web-Administratoren die in diesem Feld gearbeitet haben.
- https://wiki.nginx.org/Main - Das nginx wiki.
- https://github.com/h5bp/server-configs-nginx - H5BP's nginx-Konfigurationen.