Nginx
설치
www-servers/nginx 꾸러미를 바로 설치하기 전에, 먼저 nginx에 대한 USE 플래그를 살펴보는 것이 좋습니다.
확장 USE 플래그
nginx는 기능을 확장하기 위해 모듈을 활용합니다. 모듈식 접근을 간편하게 하기 위해 nginx에서는 확장 USE 플래그(USE_EXPAND )를 활용하여 어떤 모듈을 설치해야 할지 표기합니다.
- HTTP 관련 모듈은 NGINX_MODULES_HTTP 변수로 활성화할 수 있습니다.
- 전자메일 관련 모듈은 NGINX_MODULES_MAIL 변수로 활성화할 수 있습니다.
- 서드파티 모듈은 NGINX_ADD_MODULES 변수로 활성화할 수 있습니다.
이 변수는 /etc/portage/make.conf에 설정해야 합니다. 설명은 /usr/portage/profiles/desc/nginx_modules_http.desc 와 /usr/portage/profiles/desc/nginx_modules_mail.desc 에 있습니다.
예를 들어 fastcgi 모듈을 활성화하려면:
/etc/portage/package.usewww-servers/nginxNGINX_MODULES_HTTP:fastcgi
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
USE 플래그를 설정한 후 www-servers/nginx 를 설치하십시오:
root #emerge --ask www-servers/nginx설치 검증
기본 nginx 설정에서는 가상 서버의 루트 디렉터리를 /var/www/localhost/htdocs 로 설정했습니다. 그러나 bug #449136 버그 때문에 nginx를 빌드하고 나면 index 파일을 만들지 않고 /var/www/localhost 디렉터리만 만듭니다. 기본 설정을 동작하게 하려면 /var/www/localhost/htdocs 디렉터리를 만들고 간단한 index 파일을 넣으십시오:
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 꾸러미는 관리자가 서비스를 멈추고 시작하고 다시 시작하도록 하는 초기화 서비스 스크립트를 설치합니다. 다음 명령을 실행하여 nginx 서비스를 시작하십시오:
root #/etc/init.d/nginx startIf using systemd, use the following command to start NGINX:
root #systemctl start nginx.servicenginx가 동작중인지 확인하려면 웹 브라우저 또는 curl 같은 다음 명령행 웹 도구에게 http://localhost 주소를 제시하십시오:
user $curl http://localhost 설정
nginx 설정은 /etc/nginx/nginx.conf 파일에서 다룹니다.
단일 사이트 접근
다음 예제는 (PHP 같은) 동적 기능을 뺀 단일 사이트 접근을 보여줍니다.
/etc/nginx/nginx.conf젠투 기본 설정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;
}
}
다중 사이트 접근
설정을 여러 파일로 쪼개기 위해 include 지시어를 활용할 수 있습니다.
/etc/nginx/nginx.conf다중 사이트 설정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;
include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/local.conf단순 호스트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;
}
/etc/nginx/conf.d/local-ssl.conf단순 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 지원
다음 줄을 추가하여 nginx 설정에서 PHP 지원을 활성화하도록 하십시오. 이 예제에서 nginx는 유닉스 소켓을 통해 PHP 프로세스와 정보를 교환합니다.
/etc/nginx/nginx.confPHP 지원 활성화...
http {
...
server {
...
location ~ \.php$ {
# Test for non-existent scripts or throw a 404 error
# Without this line, nginx will blindly send any request ending in .php to php-fpm
try_files $uri =404;
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/run/php-fpm.socket;
}
}
}
이 설정 과정을 지원하려면, PHP에서 FastCGI 프로세스 관리자 지원(dev-lang/php )과 빌드해야 하며, 이 지원 사항은 fpm USE 플래그를 통해 처리할 수 있습니다:
root #echo "dev-lang/php fpm" >> /etc/portage/package.usefpm USE 플래그를 활성화 한 상태에서 php를 다시 빌드하십시오.
root #emerge --ask dev-lang/php유닉스 소켓 통신을 사용하는 것이 적당하며 권장하는 설정 방식입니다
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 php.ini 파일에서 시간대를 설정하십시오. 하단의 파일 상자에서<PUT_TIMEZONE_HERE> 부분을 적합한 시간대 정보로 바꾸십시오:
/etc/php/fpm-php5.5/php.iniphp.ini에서 시간대 설정date.timezone=<PUT_TIMEZONE_HERE>
php-fpm 데몬을 시작하십시오:
root #/etc/init.d/php-fpm start기본 런레벨에 php-fpm을 추가하십시오:
root #rc-update add php-fpm default바뀐 설정 내용으로 nginx를 다시 불러오십시오:
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 주소 접근 목록
다음 예제에서는 각각의 URL(이 경우 /nginx_status)에서 다음에 대해서만 접근을 허용하는 방법을 보여줍니다
- 각각의 호스트 (예: 192.0.2.1 127.0.0.1)
- IP 네트워크 (예: 198.51.100.0/24)
/etc/nginx/nginx.conf/nginx_status 페이지의 IP 접근 목록 활성화 및 설정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;
}
}
}
기본 인증
nginx에서는 사용자 이름과 암호를 검증하는 방식으로 자원 접근을 제한할 수 있습니다:
/etc/nginx/nginx.conf/ 위치에 대한 사용자 인증 활성화 및 설정http {
server {
location / {
auth_basic "Authentication failed";
auth_basic_user_file conf/htpasswd;
}
}
}
The htpasswd file can be generated using:
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;
사용법
서비스 관리
OpenRC
nginx를 시작하십시오:
root #/etc/init.d/nginx startnginx를 멈추십시오:
root #/etc/init.d/nginx stopnginx를 기본 런레벨에 추가하십시오:
root #rc-update add nginx defaultReload NGINX configuration without dropping connections:
root #rc-service nginx reloadnginx를 다시 시작하십시오:
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 nginx문제 해결
이 문제의 경우 다음 명령이 상태 문제를 해결하는데 도움을 줍니다.
설정 확인
nginx 설정에 오류가 없는지 확인하십시오:
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에 -t 옵션을 추가하여 실행하면, nginx 데몬을 실제로 시작하지 않고도 설정 파일을 확인합니다.
프로세스 실행 확인
nginx 프로세스가 실행 중인지 확인하십시오:
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
범위 주소 및 포트 확인
nginx 데몬이 올바른 TCP 포트에 대한 응답을 기다리는지 확인하십시오(HTTP에 대해서는 80, HTTPS에 대해서는 443):
root #netstat -tulpen | grep :80tcp 0 0 127.0.0.1:80 0.0.0.0:* LISTEN 0 12336835 -26092/nginx: master
추가 참조
외부 자료
- http://nginx.org/en/docs/beginners_guide.html - nginx 초보자 안내서. nginx에 대해 잘 알지 못하는 이들에게 도움을 줍니다.
- http://nginx.com/resources/admin-guide/ - ngnix 관리자 안내서. 현업에서 일하는 웹 관리자에게 도움을 줍니다.
- http://wiki.nginx.org/Main - nginx 위키.
- https://github.com/h5bp/server-configs-nginx - H5BP nginx 설정.