Nginx

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

nginx는 견고하고 작은 고성능 웹 서버이며 역방향 프록시 서버입니다. 아파치 또는 lighttpd와 같은 현존하는 유명 웹서버 대신 사용하기에 좋습니다.

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/make.conf
NGINX_MODULES_HTTP="fastcgi"

NGINX_MODULES_HTTP 기본 값을 엎어 쓰고 fastcgi로 설정합니다. NGINX_MODULES_HTTP 기본 값을 덮어쓰지 않고 fastcgi 모듈을 활성화하려면, 다음 USE 플래그 표기를 /etc/portage/package.use 에 지정할 수 있습니다:

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

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

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 /var/www/localhost/htdocs
root #echo 'Hello, world!' > /var/www/localhost/htdocs/index.html

nginx 꾸러미는 관리자가 서비스를 멈추고 시작하고 다시 시작하도록 하는 초기화 서비스 스크립트를 설치합니다. 다음 명령을 실행하여 nginx 서비스를 시작하십시오:

root #/etc/init.d/nginx start

nginx가 동작중인지 확인하려면 웹 브라우저 또는 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.use

fpm 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-php7.1/fpm.d/www.confRunning PHP with UNIX socket support
listen = /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 reload

Alternatively, for systemd:

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

IP 주소 접근 목록

다음 예제에서는 각각의 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 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:

파일 /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:

파일 /etc/portage/package.use/nginxAdd the modules to Nginx
www-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/nginx

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

파일 /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:

파일 /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;

서드파티 모듈

서드 파티 모듈 소스를 다운로드하고 /usr/src로 옮겨놓으십시오. 선택한 nginx 모듈을 직접 컴파일한 후, /etc/portage/make.conf에 모듈 이름을 추가하십시오:

파일 /etc/portage/make.conf서드파티 모듈 추가
NGINX_ADD_MODULES="/usr/src/nginxmodule"

서드파티 모듈을 활성화하려면 nginx를 다시 빌드하십시오:

root #emerge --ask www-servers/nginx

사용법

서비스 관리

OpenRC

nginx를 시작하십시오:

root #/etc/init.d/nginx start

nginx를 멈추십시오:

root #/etc/init.d/nginx stop

nginx를 기본 런레벨에 추가하십시오:

root #rc-update add nginx default

Reload nginx configuration without dropping connections:

root #rc-service nginx reload

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

문제 해결

이 문제의 경우 다음 명령이 상태 문제를 해결하는데 도움을 줍니다.

설정 확인

nginx 설정에 오류가 없는지 확인하십시오:

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

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 :80
tcp        0      0 127.0.0.1:80            0.0.0.0:*               LISTEN      0          12336835   -26092/nginx: master

추가 참조

  • Apache - 인터넷에서 사용하는 가장 인기있는 HTTP 서버.
  • Lighttpd - 빠르고 가벼운 웹 서버

외부 자료