什么是Nginx

Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务 。其特点是占有内存少,并发能力强。
协议:BSD-like

Nginx 安装

1. 部署执行命令:apt-get install nginx

备注:若想指定版本,命令后面加上版本号,如:apt-get install nginx:1.22.0。
若部署过程中提示拉取不到,可以尝试修改源。
Ubuntu nginx 默认的部署路径为:/usr/local/etc/nginx

当然了,若想自定义路径也是可以的,比如:

./configure
 –sbin-path=/usr/local/nginx/nginx
 –conf-path=/usr/local/nginx/nginx.conf
 –pid-path=/usr/local/nginx/nginx.pid
 –with-http_ssl_module
 –with-pcre=…/pcre2-10.39
 –with-zlib=…/zlib-1.2.11

2. 查看Nginx 部署情况:nginx -v

3. 启动Nginx: service nginx start 或者进入sbin 目录启动Nginx ./nginx -s start

打开浏览器访问虚拟机所在的IP,若访问通,则说明部署OK。

Nginx 主要配置

#设置worker进程的用户,指的linux中的用户,会涉及到nginx操作目录或文件的一些权限,默认为 nobody
user  nobody;
#worker进程工作数设置,一般来说CPU有几个,就设置几个,或者设置为N-1也行;默认配置的 auto
worker_processes  1;

#全局错误日志及PID文件及存放路径。nginx 日志级别 debug | info | notice | warn | error | crit | alert | emerg ,错误级别从左到右越来越大
#crit : 关键问题。需要立即采取行动;alert -警报。必须立即采取行动;emerg - 紧急情况。系统处于无法使用的状态;默认notice。
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#设置nginx进程 pid
#pid        logs/nginx.pid

#工作模式及连接数上限
events {
	# 默认使用epoll,可以不配置
	use epoll;
    #单个后台work process进程的最大并发链接数。若服务器性能不错,可以调大,比如10240
    worker_connections  1024;  
}

#网页信息
http {
    #设定mine类型,类型由mine。type文件定义。若有一部分自定义的内容,也可以include 引入进来。
    include       mime.types;
    default_type  application/octet-stream;
  
    #设定日志格式 
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    
    #日志文件存储路径/usr/local/...(nginx的安装目录)
    #access_log  logs/access.log  main;
    #sendfile 指令 指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,建议为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off ,以平衡磁盘与网络I/O处理速度,降低系统的uptime. sendfile 启用后才能使用 tcp_nopush ,是指当数据表累积一定大小后才发送,提高了效率。
    sendfile        on;
    #tcp_nopush     on;
    
    #  keepalive_timeout 设置客户端与服务端请求的超时时间,保证客户端多次请求的时候不会重复建立新的连接,节约资源损耗。
    #keepalive_timeout  0;
    keepalive_timeout  65;
    
    #开启gzip压缩 如果没有开启gzip,用户访问我们的时候就是以原图来访问。
    gzip  on;
    #小于1K的文件不适合压缩,下限是1k
    gzip_min_lenth 1k;
    #缓存的内存空间--4个16进制数据流
    gzip_buffers 4 16k;
    #http版本
    gzip_http_version 1.1
    #开启判断客户端和浏览器是否支持gzip
    gzip_vary on;
    #设定虚拟主机配置
    server {
        #监听80端口
        listen       80;
        #定义使用访问的网址
        server_name  localhost;
        #设置字符编码
        #charset utf-8;
        #设定本虚拟主机的访问日志
        #access_log  logs/host.access.log  main;
        #允许跨域请求的域,*代表所有
		add_header 'Access-Control-Allow-Origin' *;
		#允许带上cookie请求
		add_header 'Access-Control-Allow-Credentials' 'true';
		#允许请求的方法,比如 GET/POST/PUT/DELETE
		add_header 'Access-Control-Allow-Methods' *;
		#允许请求的header
		add_header 'Access-Control-Allow-Headers' *;
		
		#对源站点验证,防盗链配置
		valid_referers *.test.com;
		#非法引入会进入下方判断
		if ($invalid_referer) {
		return 404;
		}
		 #
		 默认请求,优先级最低的配置
		 location / {
            #定义服务器的默认网站根目录位置
            root   html;
            # 匹配任何请求,因为所有请求都是以"/"开始,但是更长字符匹配或者正则表达式匹配会优先匹配,定义首页索引文件的名称
            index  index.html index.htm;
        }
        
        #配置Nginx缓存。
        #= 用于不含正则表达式的 url 前,要求字符串与 url 严格匹配,匹配成功就停止向下搜索并处理请求。
        #~:用于表示 url 包含正则表达式,并且区分大小写。
        #~*:用于表示 url 包含正则表达式,并且不区分大小写。
        #^~:用于不含正则表达式的 url 前,要求 Nginx 服务器找到表示 url 和字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再匹配。
        
        location ~.*\.(jpg|png|gif)$ {
          expires 30d; #缓存存放30天,然后自动清除
        }
        location ~.*\.(css|js)? $ {
          expires 1h; #缓存存放1小时
        }
		#error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #定义错误页面
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        # slow_start 表示权重60S内慢慢上升到6
        # max_conns 限制每台server的连接数,用于保护避免过载,可起到限流作用
        # upstream 指令参数 down 表示服务节点不可用、backup 表示当前服务器节点是备用机,只有在其他的服务器都宕机以后,自己才会加入到集群中
        # max_fails :表示失败几次,则标记server已宕机,剔出上游服务。
		# fail_timeout :表示失败的重试时
		# 负载均衡模式:1、 least_conn; 最少连接;2.ip_hash; IP 哈希;3. 默认:round-robin,轮询
        upstream tomcats {
       			 least_conn;
				server 192.***.***.**1:8080 weight=6  max_conns=2 slow_start=60s;
				server 192.***.***.**2:8080 weight=2;
				server 192.***.***.**3:8080 weight=2;
		}
	  # 对 “/” 启用反向代理,对上面的实例  
    location / {
      proxy_pass http://127.0.0.1:3000;  # 设置要代理的 uri,注意最后的 /。可以是 Unix 域套接字路径,也可以是正则表达式。
      proxy_redirect off; # 设置后端服务器“Location”响应头和“Refresh”响应头的替换文本
      proxy_set_header X-Real-IP $remote_addr; # 获取用户的真实 IP 地址
      #后端的Web服务器可以通过 X-Forwarded-For 获取用户真实IP,多个 nginx 反代的情况下,例如 CDN。
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      #以下是一些反向代理的配置,可选。
      proxy_set_header Host $host; # 允许重新定义或者添加发往后端服务器的请求头。
      client_max_body_size 10m; #允许客户端请求的最大单文件字节数
      client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
      proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
      proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
      proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
      proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
      proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的设置
      proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
      proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传
    }

    # 本地动静分离反向代理配置 , 静态文件由nginx直接读取不经过tomcat或resin
    location ~ .(jsp|jspx|do)?$ {
      root    /data/html;
    }
    
    # 所有静态文件由nginx直接读取不经过tomcat或resin
    location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)${
      root    /data/www/ospring.pw/public;
      expires 15d;
    }
    location ~ ^/(upload|html)/  {
      root    /data/www/ospring.pw/public/html;
      expires 30d;
    }

    #这里可以配置多台虚拟主机
    # another virtual host using mix of IP-, name-, and port-based configuration
    #配置虚拟机
    #server {
    # 配置监听端口,只要端口不同就是不同的虚拟主机
    #    listen       8000;
    #    listen       somename:8080;
    #配置访问域名
    #    server_name  somename  alias  another.alias;
    
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    web服务器配置
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

nginx 组网

Nginx 特色

  1. 零拷贝
  2. IO 多路复用
  3. Master 和 worker 合作。Master负责连接,worker 负责干活。worker 通过抢占方式获取连接。

Nginx 命令

-s 代表信号,signal
nginx -s stop — 快速停止
nginx -s quit — 相对于stop,它会等worker执行完成才停止
nginx -s reload — 重新加载配置文件
nginx -s reopen — 重新打开日志文件
nginx -s start —启动