一、Nginx简介

常用命令

启动 
nginx -c /usr/local/nginx/conf/nginx.conf  #指定配置文件启动
nginx -p `pwd`/ -c conf/nginx.conf         #设置前缀路径

检查 nginx.conf配置文件
nginx -t

重启
nginx -s reload

停止

nginx -s stop

二、名词解释

主配置文件路径

/etc/nginx/nginx.conf

配置文件说明

  • main:全局配置,与具体业务功能无关的一些参数,比如工作进程数,运行的身份等
  • event:事件处理模块,包含nginx中所有处理连接的设置
  • http:http服务器配置
    • upstream:负载均衡配置
    • server:虚拟主机配置
      • location:根据用户请求的URI来执行不同的应用

alt

  • 示例1:
    # 全局配置
    user  www www;			# 指定nginx进程使用什么用户启动
    worker_processes 4;		# 指定启动多少进程来处理请求,一般情况下设置成CPU的核数,如果开启了ssl和gzip更应该设置成与逻辑CPU数量一样甚至为2倍,可以减少I/O操作。使用grep ^processor /proc/cpuinfo | wc -l查看CPU核数。
    worker_cpu_affinity 0001 0010 0100 1000;		# 在高并发情况下,通过设置将CPU和具体的进程绑定来降低由于多核CPU切换造成的寄存器等现场重建带来的性能损耗。如worker_cpu_affinity 0001 0010 0100 1000; (四核)
    error_log  /var/logs/nginx_error.log  crit;		# error_log是个主模块指令,用来定义全局错误日志文件。日志输出级别有debug、info、notice、warn、error、crit可供选择,其中,debug输出日志最为最详细,而crit输出日志最少
    pid        /usr/local/webserver/nginx/nginx.pid;# 指定进程pid文件的位置
    worker_rlimit_nofile 65535;						# 用于指定一个nginx进程可以打开的最多文件描述符数目,这里是65535,需要使用命令“ulimit -n 65535”来设置
    # include /opt/nlo/nginx/conf/ngx_core.conf;	# 一般全局配置较多情况下,常用include引用配置文件
    
    events {
            use epoll;						# use是个事件模块指令,用来指定Nginx的工作模式
            worker_connections      65536;	# 每一个worker进程能并发处理(发起)的最大连接数
            include /opt/nlo/nginx/conf/ngx_events.conf;	# 配置较多情况下include引用配置文件
    }
    
    http {
    
            include /opt/nlo/nginx/conf/ngx_http.conf;			# http配置
    
            include /opt/nlo/nginx/conf/olivehc_upstream.conf;	# 负载均衡相关配置
    
            include /opt/nlo/nginx/conf/server-*.conf;			# 各种虚拟主机配置
    }
    
    
  • 示例2
user  www www;
worker_processes  2;
pid        logs/nginx.pid;
...

events {
    use epoll;
    ...
}

http {
    include       mime.types;
    ...
  	# gzip压缩功能设置
    gzip on;
  	...
  	# http_proxy 设置
    client_max_body_size   10m;
	...
    
  	# 设定负载均衡后台服务器列表 
    upstream  backend  { 
              #ip_hash; 
              server   192.168.10.100:8080 max_fails=2 fail_timeout=30s ;  
              server   192.168.10.101:8080 max_fails=2 fail_timeout=30s ;  
    }
    
  	# 很重要的虚拟主机配置,多个虚拟机可以复制修改此部分
    server {
        listen       80;
        ...
        #对 / 所有做负载均衡+反向代理
        location / {
            root   /apps/oaapp;
            ...
        }
        
        #静态文件,nginx自己处理,不去backend请求后端的服务
        location  ~* /download/ {  
            root /data/app/nginx/downloads;  
        }
        ...
    }
}

三、基本使用

  • 常用命令
启动
./nginx 

检查 nginx.conf配置文件
./nginx -t

重启
./nginx -s reload

停止

./nginx -s stop
  • aa

四、概念理解

1. 负载均衡

五、编程技巧

1. 调试代码

local cjson = require("cjson")

-- table  to json 示例:
local t = {
    aaa = {
        ips = "111.111.111.111",
        port = "443"
    }
}
local s = cjson.encode(t)

-- json to table
a= '{"configlist":{"sd_new_old_cp_switch":{"vod":"gitvlive"}}}'
atb=cjson.decode(a)