Nginx
nginx ufak, güçlü ve yüksek performanslı bir web/ters proxy (reverse proxy) sunucu yazılımıdır. Apache ve lighttpd gibi popüler web sunucu yazılımları için iyi bir alternatiftir.
Kurulum
www-servers/nginx paketini kurmadan önce, kullanabildiği USE bayraklarına göz atalım.
Genişletilmiş USE bayrakları
Nginx yeteneklerini artırmak için modülleri kullanır. Bu yaklaşımın faydalarını kullanmak için kurulumu sırasında hangi modüllerin kullanılacağını bazı USE setleri ile ayarlayabilirsiniz.
- HTTP ile ilgili modüller
NGINX_MODULES_HTTPdeğişkeniyle, - E-posta özellikleri ile ilgili modüller
NGINX_MODULES_MAILdeğişkeniyle, - Diğer üçüncü parti modüller de
NGINX_ADD_MODULESdeğişkeni ile aktifleştirilebilir.
Bu değişkenler /etc/portage/make.conf dosyasında tanımlanmalıdır. Detaylı açıklamaları /usr/portage/profiles/desc/nginx_modules_http.desc ve /usr/portage/profiles/desc/nginx_modules_mail.desc adreslerinde bulunabilir.
Örneğin fastcgi modülünü etkinleştirmek için:
/etc/portage/package.use/nginxwww-servers/nginxNGINX_MODULES_HTTP:fastcgi
USE bayrakları
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
USE bayraklarıı ayarladıysanız, www-servers/nginx paketini kurun:
root #emerge --ask www-servers/nginxKurulumun onaylanması
The default NGINX configuration defines an HTTP virtual server listening on loopback address but does not define a root directory. To test out the installation, use an existing directory or create a new root directory, for example /var/www/localhost/htdocs:
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/htdocsnginx paketi, servisi durdurmak, başlatmak ve yeniden başlatmak için yardımcı olan bir servis betiği ile gelir. nginx servisini başlatmak için:
root #/etc/init.d/nginx startIf using systemd, use the following command to start NGINX:
root #systemctl start nginx.servicenginx'in doğru şekilde çalıştığına emin olmak için, web tarayıcınızdan http://localhost adresine gidebilir veya curl gibi bir komut satırı aracını kullanabilirsiniz:
user $curl http://localhost Yapılandırma
nginx yapılandırması /etc/nginx/nginx.conf dosyası üzerinde düzenlenir.
Tek site erişimi
Aşağıdaki örnek, (PHP gibi) dinamik özellikleri olmayan tek site yapılandırması içindir.
/etc/nginx/nginx.confÖntanımlı Gentoo yapılandırması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 on;
gzip_min_length 1100;
gzip_buffers 4 8k;
gzip_types text/plain;
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;
}
}
Birden çok site erişimi
Birden fazla yapılandırma dosyasında daha kolay yönetim sağlamak için include yönergesi kullanılabilir:
/etc/nginx/nginx.confBirden fazla site sunumuuser 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 on;
gzip_min_length 1100;
gzip_buffers 4 8k;
gzip_types text/plain;
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.confÖrnek bir siteserver {
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.confÖrnek bir SSL destekli siteserver {
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 desteği
PHP desteğini açmak için aşağıdaki satırları nginx yapılandırma dosyasına ekleyebilirsiniz. Bu örnekte nginx PHP ile iletişimini UNIX soketi üzerinden yapmakta.
/etc/nginx/nginx.confPHP desteği örneği...
http {
...
server {
...
location ~ \.php$ {
# Olmayan dosyalari test edip 404 hatasi ver
# Bu satir olmazsa nginx gelen her .php ile biten istegi incelemeden php-fpm e gonderir
try_files $uri =404;
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/run/php-fpm.socket;
}
}
}
Bu şekilde çalışabilmek için PHP FastCGI desteği ile (php-fpm) derlenmiş olmalıdır, bu da fpm bayrağı ile sağlanır:
root #echo "dev-lang/php fpm" >> /etc/portage/package.useArdından PHP'yi fpm USE bayrağıyla tekrar derleyelim:
root #emerge --ask dev-lang/phpUNIX soket iletişimi önerilen yöntemdir
Using UNIX socket communication is the preferred and recommended configuration
For PHP 7.0 and newer PHP versions use following configuration:
/etc/php/fpm-php8.2/fpm.d/www.confRunning PHP with UNIX socket supportlisten=/run/php-fpm.socket listen.owner=nginx
php-fpm'e ait php.ini dosyasında zaman dilimini ayarlayın. Bunun için ilgili zaman dilimini aşağıda <ZAMAN_DİLİMİ> ile belirtilen yere ekleyin:
/etc/php/fpm-php5.5/php.iniphp.ini dosyasında zaman dilimi ayarıdate.timezone=<ZAMAN DİLİMİ>
Ardından php-fpm servisini başlatın:
root #/etc/init.d/php-fpm startphp-fpm servisini açılışta başlamak üzere öntanımlı çalışma seviyesine ekleyin:
root #rc-update add php-fpm defaultnginx servisini yeni yapılandırma ile yeniden yükleyin:
root #/etc/init.d/nginx reloadAlternatively, for systemd:
root #systemctl enable php-fpm@8.2
root #systemctl start php-fpm@8.2
root #systemctl restart nginx.serviceIP adresiyle eirşim kısıtlaması
Sıradaki örneğimiz belirlediğimiz bir sayfaya (bu örnekte /nginx_status) sadece seçtiğimiz kaynaklardan ulaşılabilmesi, bunlar aşağıdaki gibi:
- IP adresleri (Örn. 192.0.2.1 127.0.0.1)
- IP ağ blokları (Örn. 198.51.100.0/24)
olabilir.
- certain hosts (e.g. 192.0.2.1 127.0.0.1)
- and IP networks (e.g. 198.51.100.0/24)
/etc/nginx/nginx.conf/nginx_status sayfası için IP adres kısıtlaması örneğihttp {
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;
}
}
}
Basit yetkilendirme
nginx kullanıcı adı ve parola sorup yetkilendirme yapma desteğine de sahiptir:
/etc/nginx/nginx.conf/ lokasyonu için kullanıcı adı - parola yetkilendirmesihttp {
server {
location / {
auth_basic "Authentication failed";
auth_basic_user_file conf/htpasswd;
}
}
}
htpasswd dosyası aşağıdaki şekilde oluşturulabilir:
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.
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/geoipupdateEnter the account and license key:
/etc/GeoIP.confAdd your account infoAccountID 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:
/etc/portage/package.use/nginxAdd the modules to NGINXwww-servers/nginx NGINX_MODULES_HTTP: geo geoip2
The geoip module only supports the GeoIP legacy database.
Rebuild NGINX with the third party modules enabled:
root #emerge --ask www-servers/nginxOnce NGINX has been rebuild, point NGINX to the databases and the GeoIP2 variables:
/etc/nginx/nginx.confPointing to the GeoIP2 databases and its valueshttp {
# ...
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:
/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;
Kullanım
Servis kontrolü
OpenRC
Nginx'i başlatmak:
root #/etc/init.d/nginx startNginx'i durdur:
root #/etc/init.d/nginx stopNginx'i öntanımlı çalışma seviyesine ekle:
root #rc-update add nginx defaultReload NGINX configuration without dropping connections:
root #rc-service nginx reloadNginx'i yeniden başlat:
root #/etc/init.d/nginx restartsystemd
Start NGINX web server:
root #systemctl start nginxStop NGINX web server:
root #systemctl stop nginxCheck the status of the service:
root #systemctl status nginxEnable service to start automatically on system reboot:
root #systemctl enable nginxReload NGINX configuration without dropping connections:
root #systemctl reload nginxRestart the NGINX service:
root #systemctl restart nginxOlası Problemler
Problem yaşarsanız aşağıdaki komutlar sebebini bulmanıza yardımcı olabilir.
Yapılandırmayı onaylama
nginx ayar dosyalarının belirgin bir hatası olmadığını kontrol etmek için:
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
nginx komutunu -t parametresi ile çalıştırırsanız, servis başlatmadan sadece kontrolleri yapacaktır.
İşlemlerin çalıştığına emin olun
nginx işlemlerinin çalıştığına emin olun:
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
Adres ve portların kullanımda olduğuna emin olun
nginx servisinin doğru portları dinlediğinden emin olun (HTTP için 80 ve HTTPS için 443 gibi):
root #netstat -tulpen | grep :80tcp 0 0 127.0.0.1:80 0.0.0.0:* LISTEN 0 12336835 -26092/nginx: master
Ayrıca bkz.
Harici kaynaklar
- http://nginx.org/en/docs/beginners_guide.html - nginx hakkında yeni başlayanlara yönelik bir klavuz.
- http://nginx.com/resources/admin-guide/ - Yönetimini yapanlar için Nginx admin klavuzu.
- http://wiki.nginx.org/Main - nginx Wiki.
- https://github.com/h5bp/server-configs-nginx - H5BP nginx yapılandırması.