Nginx服务器基本的模块配置和使用全攻略

2019-10-17 19:30:17刘景俊

--with-http_stub_status_module : 用来监控 Nginx 的当前状态
--with-http_realip_module : 通过这个模块允许我们改变客户端请求头中客户端IP地址值(例如X-Real-IP 或 X-Forwarded-For),意义在于能够使得后台服务器记录原始客户端的IP地址
--add-module=PATH : 添加第三方外部模块,如nginx-sticky-module-ng或缓存模块。每次添加新的模块都要重新编译(Tengine可以在新加入module时无需重新编译)
再提供一种编译方案:

./configure 
> --prefix=/usr 
> --sbin-path=/usr/sbin/nginx 
> --conf-path=/etc/nginx/nginx.conf 
> --error-log-path=/var/log/nginx/error.log 
> --http-log-path=/var/log/nginx/access.log 
> --pid-path=/var/run/nginx/nginx.pid 
> --lock-path=/var/lock/nginx.lock   
> --user=nginx 
> --group=nginx 
> --with-http_ssl_module 
> --with-http_stub_status_module 
> --with-http_gzip_static_module 
> --http-client-body-temp-path=/var/tmp/nginx/client/ 
> --http-proxy-temp-path=/var/tmp/nginx/proxy/ 
> --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ 
> --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi 
> --with-pcre=../pcre-7.8
> --with-zlib=../zlib-1.2.3

1.3 启动关闭nginx

## 检查配置文件是否正确
# /usr/local/nginx-1.6/sbin/nginx -t 
# ./sbin/nginx -V   # 可以看到编译选项

## 启动、关闭
# ./sbin/nginx    # 默认配置文件 conf/nginx.conf,-c 指定
# ./sbin/nginx -s stop

或 pkill nginx

## 重启,不会改变启动时指定的配置文件
# ./sbin/nginx -s reload

kill -HUP `cat /usr/local/nginx-1.6/logs/nginx.pid`

当然也可以将 nginx 作为系统服务管理,下载 nginx 到/etc/init.d/,修改里面的路径然后赋予可执行权限。

# service nginx {start|stop|status|restart|reload|configtest}

1.4 yum安装
yum安装rpm包会比编译安装简单很多,默认会安装许多模块,但缺点是如果你想以后安装第三方模块那就没办法了。

# vi /etc/yum.repo.d/nginx.repo 
[nginx] 
name=nginx repo 
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ 
gpgcheck=0 
enabled=1

剩下的就yum install nginx搞定,也可以yum install nginx-1.6.3安装指定版本(前提是你去packages里看到有对应的版本,默认是最新版稳定版)。

2. nginx.conf配置文件
Nginx配置文件主要分成四部分:main(全局设置)、server(主机设置)、upstream(上游服务器设置,主要为反向代理、负载均衡相关配置)和 location(URL匹配特定位置后的设置),每部分包含若干个指令。main部分设置的指令将影响其它所有部分的设置;server部分的指令主要用于指定虚拟主机域名、IP和端口;upstream的指令用于设置一系列的后端服务器,设置反向代理及后端服务器的负载均衡;location部分用于匹配网页位置(比如,根目录“/”,“/images”,等等)。他们之间的关系式:server继承main,location继承server;upstream既不会继承指令也不会被继承。它有自己的特殊指令,不需要在其他地方的应用。