Nginx服务器搭建和基本配置详解

2019-10-17 19:59:40于海丽

Nginx(engine X) 是一个高性能的 HTTP 服务器和反向代理服务器,这款软件开发的目的是为了解决 C10k 问题。

Nginx 的架构利用了许多现代操作系统的特性,以实现一个高性能的 HTTP 服务器。例如在 Linux 系统上,Nginx 使用了 epoll,sendfile,File AIO,DIRECTIO 等机制,使得 Nginx 不仅性能高效,而且资源占用率非常低,官方宣称 nginx 维持 10000 个非活动的 HTTP keep-alive 连接仅需要 2.5M 内存。

Nginx会按需同时运行多个进程:一个主进程(master)和几个工作进程(worker),配置了缓存时还会有缓存加载器进程(cache loader)和缓存管理器进程(cache manager)等。所有进程均是仅含有一个线程,并主要通过“共享内存”的机制实现进程间通信。主进程以 root 用户身份运行,而worker、cache loader 和 cache manager 均应以非特权用户身份运行。

1. 安装 nginx
在 CentOS6 版本的 EPEL 源中,已经加入了 nginx 的 rpm 包,不过此 RPM 包版本较低。如果需要更新版本,可以使用官方制作的 rpm 包,或者使用源码包编译安装。

还可以使用一些二次开发功能增强的 nginx 版本,例如淘宝的 Tengine 和 OpenResty 都是不错的选择。

1.1 常用编译参数

--prefix=PATH:指定 nginx 的安装目录
--conf-path=PATH:指定 nginx.conf 配置文件路径
--user=NAME:nginx 工作进程的用户
--with-pcre:开启 PCRE 正则表达式的支持
--with-http_ssl_module:启动 SSL 的支持
--with-http_stub_status_module:用于监控 Nginx 的状态
--with-http-realip_module:允许改变客户端请求头中客户端 IP 地址
--with-file-aio:启用 File AIO
--add-module=PATH:添加第三方外部模块
这里提供一个完整的编译方案:

--prefix=/usr/local/nginx
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--http-client-body-temp-path=/var/tmp/nginx/client_body
--http-proxy-temp-path=/var/tmp/nginx/proxy
--http-fastcgi-temp-path=/var/tmp/nginx/fastcgi
--http-uwsgi-temp-path=/var/tmp/nginx/uwsgi
--pid-path=/var/run/nginx.pid
--lock-path=/var/lock/nginx
--user=nginx
--group=nginx
--with-file-aio
--with-http_ssl_module
--with-http_realip_module
--with-http_sub_module
--with-http_gzip_static_module
--with-http_stub_status_module
--with-pcre
1.2 nginx 的启动和关闭

启动 nginx:

# nginx -c /etc/nginx/nginx.conf 


关闭 nginx

# nginx -s stop


重读配置文件

# nginx -s reload
# pkill -HUP nginx


重新打开日志文件