Nginx学习笔记

一、Nginx

1、Nginx简介

Nginx是一款高性能的、轻量级的Web 服务器/反向代理服务器电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。由俄罗斯的程序设计师Igor Sysoev所开发,供俄国大型的入口网站及搜索引擎Rambler(俄文:Рамблер)使用。
其特点是占有内存少,并发能力强,事实上Nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用Nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

官网地址:http://Nginx.org/

2、Nginx安装

  • 1.安装c所需要的环境

    yum install gcc-c++
    yum install -y pcre pcre-devel
    yum install -y zlib zlib-devel
    yum install -y openssl openssl-devel
    
  • 2.解压ngnix到/opt/install
    tar -zxvf 压缩包名称 -C /opt/install

  • 3.使用configure脚本 生成可编译的makeFile文件 (在解压目录下)
    先创建/var/temp/nginx 目录:mkdir -p /var/temp/nginx
    然后,在解压目录下执行下面的命令

    ./configure \
    --prefix=/usr/local/nginx \
    --pid-path=/var/run/nginx/nginx.pid \
    --lock-path=/var/lock/nginx.lock \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --with-http_gzip_static_module \
    --http-client-body-temp-path=/var/temp/nginx/client \
    --http-proxy-temp-path=/var/temp/nginx/proxy \
    --http-fastcgi-temp-path=/var/temp/nginx/fastcgi \
    --http-uwsgi-temp-path=/var/temp/nginx/uwsgi \
    --http-scgi-temp-path=/var/temp/nginx/scgi
    
  • 4.执行编译、安装
    编译:make
    安装:make install

  • 5.启动nginx
    在nginx的安装目录的sbin目录下( /usr/local/nginx/sbin)执行:./nginx

3、配置开机自启nginx:

  • 1.编写shell脚本
    这里使用的是编写shell脚本的方式来处理

    vi /etc/init.d/nginx (输入下面的代码)

    #!/bin/bash
    # nginx Startup script for the Nginx HTTP Server
    # it is v.0.0.2 version.
    # chkconfig: - 85 15
    # description: Nginx is a high-performance web and proxy server.
    #              It has a lot of features, but it's not for everyone.
    # processname: nginx
    # pidfile: /var/run/nginx.pid
    # config: /usr/local/nginx/conf/nginx.conf
    nginxd=/usr/local/nginx/sbin/nginx
    nginx_config=/usr/local/nginx/conf/nginx.conf
    nginx_pid=/var/run/nginx.pid
    RETVAL=0
    prog="nginx"
    # Source function library.
    . /etc/rc.d/init.d/functions
    # Source networking configuration.
    . /etc/sysconfig/network
    # Check that networking is up.
    [ ${NETWORKING} = "no" ] && exit 0
    [ -x $nginxd ] || exit 0
    # Start nginx daemons functions.
    start() {
    if [ -e $nginx_pid ];then
       echo "nginx already running...."
       exit 1
    fi
       echo -n $"Starting $prog: "
       daemon $nginxd -c ${nginx_config}
       RETVAL=$?
       echo
       [ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
       return $RETVAL
    }
    # Stop nginx daemons functions.
    stop() {
            echo -n $"Stopping $prog: "
            killproc $nginxd
            RETVAL=$?
            echo
            [ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /var/run/nginx.pid
    }
    # reload nginx service functions.
    reload() {
        echo -n $"Reloading $prog: "
        #kill -HUP `cat ${nginx_pid}`
        killproc $nginxd -HUP
        RETVAL=$?
        echo
    }
    # See how we were called.
    case "$1" in
    start)
            start
            ;;
    stop)
            stop
            ;;
    reload)
            reload
            ;;
    restart)
            stop
            start
            ;;
    status)
            status $prog
            RETVAL=$?
            ;;
    *)
            echo $"Usage: $prog {start|stop|restart|reload|status|help}"
            exit 1
    esac
    exit $RETVAL
    

    :wq 保存并退出

  • 2.设置文件的访问权限

    chmod a+x /etc/init.d/nginx (a+x ==> all user can execute 所有用户可执行)

    这样在控制台就很容易的操作nginx了:查看Nginx当前状态、启动Nginx、停止Nginx、重启Nginx…
    在这里插入图片描述

    如果修改了nginx的配置文件nginx.conf,也可以使用上面的命令重新加载新的配置文件并运行,可以将此命令加入到rc.local文件中,这样开机的时候nginx就默认启动了

  • 3.加入到rc.local文件中
    vi /etc/rc.local
    加入一行 /etc/init.d/nginx start 保存并退出,下次重启会生效。

4、Nginx命令(需要在sbin目录下)

4.1、启动(./nginx)

在nginx安装目录的sbin目录下,执行./nginx

cd /usr/local/nginx/sbin/
./nginx

注意执行./nginx启动nginx,这里可以-c指定加载的nginx配置文件,如下:
./nginx -c /usr/local/nginx/conf/nginx.conf
如果不指定-c,nginx在启动时默认加载conf/nginx.conf文件,此文件的地址也可以在编译安装nginx时指定./configure的参数(–conf-path= 指向配置文件(nginx.conf))

4.2、停止(./nginx -s stop和./nginx -s quit【推荐】)

方式1,快速停止stop:
cd /usr/local/nginx/sbin
./nginx -s stop

此方式相当于:先查出nginx进程id再使用kill命令强制杀掉进程

方式2,完整停止quit (建议使用):
cd /usr/local/nginx/sbin
./nginx -s quit

此方式停止步骤是:待nginx进程处理任务完毕进行停止

4.3、重启nginx(./nginx -s reload)

方式1,先停止再启动(建议使用):

对nginx进行重启相当于先停止nginx再启动nginx,即先执行停止命令再执行启动命令。
如下:

./nginx -s quit
./nginx
方式2,重新加载配置文件:

当nginx的配置文件nginx.conf修改后,要想让配置生效需要重启nginx,使用-s reload不用先停止nginx再启动nginx即可将配置信息在nginx中生效,如下:

./nginx -s reload

二、Nginx主要功能

nginx.conf配置文件都是 键值对 形式,用;(分号)分隔,复杂的键值对用json的格式。
其中server都对应一个虚拟主机

 server {
        listen       80;  # 监听80端口号
        server_name  localhost; # 域名为localhost

	# // 这个 /(斜杠) 相当于RequestMapping,来限制请求的
        location / {
            root   html; # // 请求要找的目录,是安装目录的html目录。
            index  index.html index.htm; # // 请求的主页是html目录下的index.html或index.htm
        }

  		  #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html  重定向服务器错误页到/50x.html
        error_page   500 502 503 504  /50x.html;  
        location = /50x.html { # 匹配到50X.html后,去安装目录下的html目录中
            root   html;
        }

    }

1、作为虚拟主机

类似于一个tomcat,可以将项目直接部署到上面运行,自己对外提供服务向外提供的都是nginx自己的资源,如静态页面,静态资源

方式1:基于端口号

在nginx.conf配置文件中,每一个server对应一个虚拟主机。

# 监听80端口号
 server {
        listen       80;
        server_name  localhost;

	# // 这个 /(斜杠) 相当于RequestMapping,来限制请求的
        location / {
            root   html; # // 请求要找的目录,是安装目录的html目录。
            index  index.html index.htm; # // 请求的主页是html目录下的index.html或index.htm
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }
	
	 server {
        listen       81;  # 监听81端口号
        server_name  localhost;

        location / { # 匹配到后,去 安装目录/html-1目录 下找index.html
            root   html-1;
            index  index.html index.htm;
        }
   
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

方式2:基于域名

注意:如果在物理机上直接输入www.teacher.com,域名先被系统解析,解析不成功会交给网络解析(如DNS,等)。我们需要让系统自己解析域名,需要修改host文件。

1. 修改host文件,在C:\Windows\System32\drivers\etc的host文件中添加:

# nginx所在ip  		域名
192.168.37.14		www.teacher.com
192.168.37.14		www.studentcom

2. nginx.conf配置文件:

	# 每一个server都对应一个虚拟主机,可以单独对外提供服务
    server {
        listen       80;
        server_name  www.teacher.com; # 监听域名为:www.teacher.com
        location / { # 主页是: 安装目录/html/index.html
            root   html;
            index  index.html index.htm;
        }   
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
	
	 server {
        listen       80;
        server_name  www.student.com;# 监听域名为:www.student.com
        location / { # 主页是: 安装目录/html-1/index.html
            root   html-1;
            index  index.html index.htm;
        }   
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

2、反向代理

反向代理: nginx自己不提供服务而是让nginx后面的tomcat服务器提供服务。即nginx代理服务器,客户端访问nginx,然后由nginx分发给服务器,而客户端不知道服务器的真实地址。
正向代理:nginx代理客户端,客户端用nginx访问服务器(这时nginx是客户端的代理,客户端访问nginx,让nginx访问目标服务器),服务器不知道客户端的真实地址。

也是修改nginx.conf,修改server
添加upstream配置,然后把upstream配置到server中的proxy_pass

server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
			# 配置代理:协议://upstream的名
			proxy_pass http://mytomcat7;
        }

        #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;
        }       
    }
	
	
	upstream mytomcat7{
		# 要代理的服务器的ip和端口号
		server 192.168.37.14:8080;
	}

3、负载均衡

nginx自己不提供服务,而是让nginx后面的tomcat服务器提供服务,抗高并发。
在这里插入图片描述

配置负载均衡:

前提:需要两台tomcat服务器。
这个jedis管理tomcat集群session中有配置两台tomcat教程:https://blog.csdn.net/BigDevil_/article/details/105227424

##################1. 配置upstream#####################
upstream sunny{
   server 192.168.1.18:8081 max_fails=1 fail_timeout=10s;  //Tomcat服务器1
   server 192.168.1.18:8082 max_fails=1 fail_timeout=10s;  //Tomcat服务器2
  }
#######################################
server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        #######################2. 配置转发############################
        proxy_pass  http://sunny;         //配置转发
        proxy_connect_timeout  1;    //是和后端建立连接的超时时间,记住不要超过 75s         proxy_read_timeout     1;       //读超时时间
        proxy_send_timeout     1;       //发送超时时间
        ###################################################
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

案例:

upstream mytomcat7{
		ip_hash;
		# 要代理的服务器的ip和端口号
		server 192.168.37.14:8080; # 服务器1
		server 192.168.37.14:8081; # 服务器2
	}
	
server {
        listen       80;
        server_name  localhost;


        location / {
            root   html;
            index  index.html index.htm;
			# 配置代理:协议://upstream的名
			proxy_pass http://mytomcat7;
        }

        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

       
    }
	

负载均衡策略:

1、轮询(默认)

每个web请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

    upstream nginxDemo {
        server 127.0.0.1:8081; #服务器A
        server 127.0.0.1:8082; #服务器B
    }
2、最少连接(least_conn)

web请求会被转发到连接数最少的服务器上。

    upstream nginxDemo {
        least_conn;
        server 127.0.0.1:8081; #服务器A
        server 127.0.0.1:8082; #服务器B
    }
3、weight 权重

指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况,weight默认是1。
#服务器A和服务器B的访问比例为:2-1;比如有3个请求,前两个会访问A,三个访问B,其它规则和轮询一样。

    upstream nginxDemo {
        server 127.0.0.1:8081 weight=2; #服务器A
        server 127.0.0.1:8082; #服务器B
    }
4、ip_hash

每个请求按访问ip的hash值分配,这样同一客户端连续的Web请求都会被分发到同一服务器进行处理,可以解决session的问题。当后台服务器宕机时,会自动跳转到其它服务器。

    upstream nginxDemo {
        ip_hash;
        server 127.0.0.1:8081 weight=2; #服务器A
        server 127.0.0.1:8082; #服务器B
    }

基于weight的负载均衡和基于ip_hash的负载均衡可以组合在一起使用。

4、last 和break, redirect 和 permanent

  • last&break

    • last:重新将rewrite后的地址在server标签中执行
    • break:将rewrite后的地址在当前location标签中执行
  • redirect&permanent

    • permanent: 永久性重定向。请求日志中的状态码为301

    • redirect:临时重定向。请求日志中的状态码为302

    从实现功能的角度上去看,permanent 和 redirect 是一样的。不存在好坏。也不存在什么性能上的问题。但是对seo会有影响,这里要根据需要做出选择

https://www.cnblogs.com/mikeluwen/p/7068279.html

三、Nginx实现动静分离

在server中添加:

	# 匹配后缀名为这些的静态资源,让其去nginx指定目录下访问静态资源,而不去服务器中访问。
	# ~是正则表达式,表示区分大小写,匹配除/n之外的所有的路径
	# \为转义,\. 表示转义.   
	# $ 表示匹配以前面这些 结尾 的路径
	location ~ \.(gif|jpg|jpeg|png|bmp|swf|css|js)$ {
		   root /usr/local/nginx/html;
		}

案例:

在ROOT的index.jsp中添加一个静态图片,并放到usr/local/nginx/html目录下

 server {
        listen       80;
        server_name  localhost;


        location / {
            root   html;
            index  index.html index.htm;
			# 配置代理:协议://upstream的名
			proxy_pass http://mytomcat7;
        }
		
		# 匹配后缀名为这些的静态资源,让其去nginx指定目录下访问静态资源,而不去服务器中访问。
		location ~ \.(gif|jpg|jpeg|png|bmp|swf|css|js)$ {
		   root /usr/local/nginx/html;
		}
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }    
    }
	
	
	upstream mytomcat7{
		ip_hash;
		# 要代理的服务器的ip和端口号
		server 192.168.37.14:8080; # 服务器1
		server 192.168.37.14:8081; # 服务器2
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值