CentOS编译Nginx

0 为什么要自己编译Nginx

在CentOS下,可以自己配置Nginx的yum源,这样安装简单,以后升级也更方便。唯一美中不足的是不能修改返回参数Server: nginx。因此,为了安全起见,需要自己修改源代码后编译Nginx。

1 下载源代码

在官网https://nginx.org/en/download.html下载最新稳定版本

解压后,修改源代码,防止信息泄露

1
2
3
4
5
SERVER_MASK=StringYouWantToShow

sed -i "s|\"nginx/\"|\"${SERVER_MASK}/\"|g" src/core/nginx.h
sed -i -e "s|Server: nginx|Server: ${SERVER_MASK}|g" src/http/ngx_http_header_filter_module.c
sed -i "s|<center>nginx</center>|<center>${SERVER_MASK}</center>|g" src/http/ngx_http_special_response.c

2 编译

1
2
3
4
yum -y install make zlib zlib-devel gcc gcc-c++ libtool openssl openssl-devel
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-pcre-jit
make
make install

3 添加系统服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/bin/bash
#
# chkconfig: - 85 15
# description: Nginx is a World Wide Web server.
# processname: nginx

nginx=/usr/local/nginx/sbin/nginx
conf=/usr/local/nginx/conf/nginx.conf
case $1 in
start)
echo -n "Starting Nginx"
$nginx -c $conf
echo " done"
;;
stop)
echo -n "Stopping Nginx"
killall -9 nginx
echo " done"
;;
test)
$nginx -t -c $conf
;;
reload)
echo -n "Reloading Nginx"
ps auxww | grep nginx | grep master | awk '{print $2}' | xargs kill -HUP
echo " done"
;;
restart)
$0 stop
$0 start
;;
show)
ps -aux|grep nginx
;;
*)
echo -n "Usage: $0 {start|restart|reload|stop|test|show}"
;;
esac

设置执行权限:chmod +x /etc/init.d/nginx

注册成服务:chkconfig --add nginx

设置开机启动:chkconfig nginx on

附: 隐藏版本号

nginx.conf里添加:

1
2
3
4
5
http {
...
server_tokens off;
...
}