Nginx

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


nginx是一个稳定、轻量、高性能的 web 服务器以及反向代理服务器。它和 Apachelighttpd 都是很好的常用的 web 服务器。

在安装 www-servers/nginx 包之前,首先请仔细查看Nginx包的USE标记。

扩展USE标记

Nginx使用模块来增加它的功能。为了简化其模块的维护工作,nginx ebuild使用扩展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。要开启fastcgi 模块且不覆盖 NGINX_MODULES_HTTP的默认值,你需要使用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 ebuild只会创建 /var/www/localhost 目录,而没有index文件。 要具有可用的默认配置,请创建/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已经正确安装,需打开浏览器并输入http://localhost地址,或使用命令行式的web工具,如curl

user $curl http://localhost

配置

nginx使用/etc/nginx/nginx.conf文件来管理配置。

单站点访问

下面展示了一个不使用动态特性(如PHP)来进行单站点访问的例子.

文件 /etc/nginx/nginx.confGentoo默认配置
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;
	}
}

多站点访问

可以使用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 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.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;
}

PHP支持

在nginx配置文件中加入下列配置来启用PHP支持。在这个例子中,nginx通过UNIX套接字与PHP进程通信。

文件 /etc/nginx/nginx.conf启用PHP支持
...
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需要在编译时开启fpmUSE标记,以加入FastCGI进程管理器(FastCGI Process Manager)支持(即php-fpm)。

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

开启fpmUSE标记后,重新编译PHP:

root #emerge --ask dev-lang/php
附注
使用UNIX套接字通信是默认配置,同时本文推荐这种配置
附注
Using UNIX socket communication is the preferred and recommended configuration

对于 PHP 7.0 和更新的 PHP 版本,使用以下配置:

文件 /etc/php/fpm-php7.1/fpm.d/www.conf启用UNIX套接字支持并运行PHP
listen = /run/php-fpm.socket
listen.owner = nginx

在文件 php.ini 中设置php-fpm的时区。将下面例子中的 <PUT_TIMEZONE_HERE>替换为正确的时区信息:

文件 /etc/php/fpm-php5.5/php.ini在php.ini中设置时区
date.timezone = <PUT_TIMEZONE_HERE>

启动 php-fpm 守护进程:

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

php-fpm 加入default runlevel:

root #rc-update add php-fpm default

重新加载 nginx 配置文件:

root #/etc/init.d/nginx reload

另外,对于 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 web 服务器:

root #rc-service nginx start

停止 nginx web 服务器:

root #rc-service nginx stop

将 nginx 添加到默认运行级别,以便在系统重启时自动启动服务:

root #rc-update add nginx default

不关闭连接,重新加载 nginx 配置:

root #rc-service nginx reload

重启nginx服务:

root #rc-service nginx restart

systemd

启动 nginx web 服务器:

root #systemctl start nginx

停止 nginx web 服务器:

root #systemctl stop nginx

检查服务状态:

root #systemctl status nginx

启用服务在系统重启时自动启动:

root #systemctl enable nginx

不关闭连接,重新加载 nginx 配置:

root #systemctl reload nginx

重启nginx服务:

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

另请参阅

外部资源