This is Gentoo's testing wiki. It is a non-operational environment and its textual content is outdated.

Please visit our production wiki at https://wiki.gentoo.org

nginx/zh-cn

From Gentoo Wiki (test)
Jump to:navigation Jump to:search
This page is a translated version of the page Nginx and the translation is 100% complete.
Other languages:

Warning: Display title "nginx/zh-cn" overrides earlier display title "Nginx".

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 模块生效:

FILE /etc/portage/make.conf
NGINX_MODULES_HTTP="fastcgi"

上面的操作会覆盖默认 NGINX_MODULES_HTTP 的默认值,并且把他设置为fastcgi。要开启fastcgi 模块且不覆盖 NGINX_MODULES_HTTP的默认值,你需要使用USE标志/etc/portage/package.use:

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

USE flags

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)来进行单站点访问的例子.

FILE /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指令将配置文件分割成多个:

FILE /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;
}
FILE /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;
}
FILE /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通过UNIX套接字与PHP进程通信。

FILE /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
Note
使用UNIX套接字通信是默认配置,同时本文推荐这种配置

检查 /etc/php/fpm-php5.5/php-fpm.conf 配置文件并添加下列配置:

FILE /etc/php/fpm-php5.5/php-fpm.conf启用UNIX套接字支持并运行PHP
listen = /run/php-fpm.socket
listen.owner = nginx

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

FILE /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

IP地址访问列表

下面的例子说明了如何使一个特定的URL地址(本例中为“/nginx_status”)只能被:

  • 当前主机(比如192.0.2.1 127.0.0.1
  • 以及IP段(198.51.100.0/24
FILE /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允许通过验证用户名和密码来限制资源的访问:

FILE /etc/nginx/nginx.conf为 / 位置启用并配置用户验证
http {
    server { 
            location / {
                   auth_basic           "Authentication failed";
                   auth_basic_user_file conf/htpasswd;
             }
     }
}

The htpasswd file can be generated using:

user $openssl passwd

TLS支持

十分建议仅支持TLS,并禁用一切已知的不安全密码。

FILE /etc/nginx/nginx.conf启用TLS和禁用不安全的密码
server {
    listen 443;
    server_name host.tld;
    ssl on;
    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;
}

ebuild在/etc/ssl/nginx/ 中提供了自签名证书。

正向加密

diffie-hellman证书可以通过 openssl 来创建:

user $openssl dhparam -out dh4096.pem 4096

第三方模块

下载第三方模块后,将其移动至 /usr/src。手动编译选中的Nginx模块,并将下列配置加入 /etc/portage/make.conf

FILE /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添加至default runlevel:

root #rc-update add nginx default

重启nginx服务:

root #/etc/init.d/nginx restart

故障排除

当遇到问题时,下列命令可以帮助你定位故障。

验证配置

验证正在运行的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 - 一个快速、轻量的web服务器。

外部资源