Nginx 添加模块
2013-05-18 by dongnan
开始之前
这篇文章发布于2013年,介绍如何为nginx添加模块,由于时间久远可能有些内容已经过时,
不过"静态添加模块"方法仍然可以使用(从1.9.11版本开始支持load_module动态加载模块),
文中的示例为nginx添加 stub_status模块,这个模块用于查看nginx的基本状态信息,对于运维人员来说很有用,建议熟练掌握使用方法。
环境描述
使用 nginx -V 数可以查看 nginx的编译参数,记好这些配置参数接下来我们还用使用:
nginx -V
nginx version: nginx/1.2.3
built by gcc 4.1.2 20080704 (Red Hat 4.1.2-46)
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx \
--with-pcre=../pcre-8.12/ \
--with-openssl=/usr/local/openssl/ \
--with-http_ssl_module --with-http_flv_module \
--with-http_gzip_static_module \
--user=www --group=www
从输出的信息来看当前的 nginx 并没有 stub_status 模块信息(默认没有启用),所以需要重新编译 nginx 并指定 stub_status模块。
操作步骤
重新编译
下载相同版本nginx源码包,复制当前的nginx编译参数,在配置项末尾添加 stub_status 模块:
tar zxf nginx-1.2.3.tar.gz
tar zxf pcre-8.12.tar.gz
cd nginx-*/
./configure --prefix=/usr/local/nginx \
--with-pcre=../pcre-8.12/ \
--with-openssl=/usr/local/openssl/ \
--with-http_ssl_module --with-http_flv_module \
--with-http_gzip_static_module \
--user=www --group=www \
--with-http_stub_status_module  
make
注意: 我们只需要 make编译就好,并不需要 make install 步骤。
替换二进制文件
替换编译好的 nginx 二进制文件:
nginx -s stop
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old
cp nginx-1.2.3/objs/nginx /usr/local/nginx/sbin/
cp: overwrite `/usr/local/nginx/sbin/nginx'? y  # 输入y
使用模块
编译并替换后就可以使用 stub_status 模块了,nginx配置文件添加如下配置项:
server
{
    #... 其它配置项省略
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}
启动nginx进程:
nginx -t && nginx
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
测试模块
访问模块的URL:
curl http://localhost/nginx_status
Active connections: 1
server accepts handled requests
 97246 97246 97246
Reading: 0 Writing: 1 Waiting: 0
信息含义如下:
- active connections:活跃的连接数量
- server accepts handled requests:收到 97246次连接 ,完成 97246次握手, 共处理 97246个请求
- reading:读取客户端的连接数。
- writing:响应数据到客户端的数量。
- waiting:开启 keep-alive 的情况下,这个值等于 active – (reading+writing)。
小结
最后来总结下文章中的知识点:
- nginx添加模块的方法。
- stub_status模块的使用方法。
- 如果不想重新编译nginx,可以尝试下load_module动态加载模块。
参考
https://nginx.org/en/docs/http/ngx_http_stub_status_module.html