Nginx服务简介及基础应用

来源:互联网 发布:家具进销存软件 编辑:程序博客网 时间:2024/04/29 15:23
###########Nginx#############
一.Nginx简介
1.Nginx是一款开源代码的高性能HTTP服务器和反向代理服务器,同时支持IMAP/POP3/SMTP代理服务
2.Nginx工作原理:
Nginx由内核和模块组成,完成工作是通过查找配置文件将客户端请求映射到一个locationblock(location是用于URL匹配的命令),location配置的命令会启动不同模块完成工作。
3.Ngnix模块分为核心模块,基础模块和第三方模块。
    核心模块:HTTP模块,EVENT模块(事件),MAIL模块。
    基础模块:HTTP Access模块,HTTP FastCGI模块,HTTP Proxy模块,HTTP Rewrite模块。
    第三方模块:HTTP Upsteam Request Hash模块,Notice模块,HTTP Access Key 模块。
4.性能优势
web服务器,处理静态文件,索引文件以及自动索引效率高。
代理服务器,快速高速反向代理,提高网站性能。
负载均衡器,内部支持Rails和PHP,,,也可支持HTTP代理服务器,对外进行服务,同时支持简单的容错和利用算法进行负载均衡。
性能方面,Nginx专门为性能设计,实现注重效率。

二.安装服务
源码编译  (源码编译的可定制性强,可根据自己的需求安装)
源码的安装一般由3个步骤组成:配置(configure)、编译(make)、安装(make install)。
Configure是一个可执行脚本,它有很多选项,在待安装的源码路径下使用命令./configure –help输出详细的选项列表。
其中--prefix选项是配置安装的路径,如果不配置该选项,安装后可执行文件默认放在/usr /local/bin,库文件默认放在/usr/local/lib,配置文件默认放在/usr/local/etc,其它的资源文件放在/usr /local/share,比较凌乱。如果配置--prefix,如:--prefix=/usr/local/lnmp/nginx 可以把所有资源文件放在/usr/local/lnmp/nginx的路径中,不会杂乱。用了—prefix选项的另一个好处是卸载软件或移植软件。当某个安装的软件不再需要时,只须简单的删除该安装目录,就可以把软件卸载得干干净净;移植软件只需拷贝整个目录到另外一个机器即可。

[root@server1 ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.12.0.tar.gz
[root@server1 ~]# tar zxf nginx-1.12.0.tar.gz                 ##解压安装包
[root@server1 ~]# ls
anaconda-ks.cfg  install.log.syslog  nginx-1.12.0.tar.gz
install.log      nginx-1.12.0
[root@server1 ~]# cd nginx-1.12.0

[root@server1 nginx-1.12.0]# yum install -y pcre-devel openssl-devel      ##安装部署nginx需要的工具


[root@server1 nginx-1.12.0]# yum install gcc -y


[root@server1 nginx-1.12.0]# useradd -M -d /usr/local/lnmp/nginx -s /sbin/nologin  -u 800 nginx
[root@server1 nginx-1.12.0]# id nginx

uid=800(nginx) gid=800(nginx) groups=800(nginx)


[root@server1 nginx-1.12.0]# ./configure --prefix=/usr/local/lnmp/nginx --user=nginx --group=nginx --with-threads --with-file-aio --with-http_ssl_module --with-http_stub_status_module


#--prefi=/usr/local/lnmp/nginx表示指定安装路径,--user=nginx指定用户,该用户必须系统中存在,--group=nginx指定组,如果没有设定默认为nobody --group=nginx --with-表示时配置后面跟的模块,--with-threads 支持线程,--with-http_ssl_module 该模块用来支持https加密服务,--with-http_stub_status_module该模块提供了nginx基础状态信息的访问接口,连接数量,处理的请求等
checking for OS
 + Linux 2.6.32-431.el6.x86_64 x86_64
checking for C compiler ... found
 + using GNU C compiler
 + gcc version: 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)

creating objs/Makefile

Configuration summary
  + using threads
  + using system PCRE library
  + using system OpenSSL library
  + using system zlib library
  .......
  nginx path prefix: "/usr/local/lnmp/nginx"
  nginx binary file: "/usr/local/lnmp/nginx/sbin/nginx"
  nginx modules path: "/usr/local/lnmp/nginx/modules"
  nginx configuration prefix: "/usr/local/lnmp/nginx/conf"
  nginx configuration file: "/usr/local/lnmp/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/lnmp/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/lnmp/nginx/logs/error.log"
  nginx http access log file: "/usr/local/lnmp/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

[root@server1 nginx-1.12.0]# make && make install    ##make编译 make install安装


make -f objs/Makefile
make[1]: Entering directory `/root/nginx-1.12.0'
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs \
        -o objs/src/core/nginx.o \
        src/core/nginx.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I sr
.......
make[1]: Leaving directory `/root/nginx-1.12.0'


[root@server1 nginx-1.12.0]# cd /usr/local/lnmp/nginx/sbin/
[root@server1 sbin]# ./nginx        ##开启ngnix服务的命令

[root@server1 sbin]# netstat -antlp    ##nginx使用80端口


Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      4429/nginx          
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      885/sshd            
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      961/master          
tcp        0      0 172.25.66.1:22              172.25.66.250:37162         ESTABLISHED 1717/sshd           
tcp        0      0 172.25.66.1:22              172.25.66.250:37157         ESTABLISHED 1676/sshd        
   
tcp        0      0 :::22                       :::*                        LISTEN      885/sshd            
tcp        0      0 ::1:25                      :::*                        LISTEN      961/master          

[root@server1 sbin]# curl  localhost -I        #访问时可直接看到nginx的版本,有安全风险
HTTP/1.1 200 OK
Server: nginx/1.12.0
Date: Thu, 20 Jul 2017 04:05:12 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 20 Jul 2017 03:48:31 GMT
Connection: keep-alive
ETag: "5970280f-264"
Accept-Ranges: bytes

anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.12.0  nginx-1.12.0.tar.gz


[root@server1 ~]# cd nginx-1.12.0
[root@server1 nginx-1.12.0]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@server1 nginx-1.12.0]# make clean         ##删除编译时生成的所有文件
rm -rf Makefile objs
[root@server1 nginx-1.12.0]# cd ..
[root@server1 ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.12.0  nginx-1.12.0.tar.gz

[root@server1 ~]# rm -fr nginx-1.12.0            ##为了保证下一个安装环境的纯净,这里彻底删除安装包


[root@server1 ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.12.0.tar.gz
重新安装
[root@server1 ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.12.0.tar.gz
[root@server1 ~]# tar zxf nginx-1.12.0.tar.gz
[root@server1 ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.12.0  nginx-1.12.0.tar.gz
[root@server1 ~]# cd nginx-1.12.0
[root@server1 nginx-1.12.0]# cd  /root/nginx-1.12.0/src/core/
[root@server1 core]# vim nginx.h         ##修改搜索时显示的版本信息
 14 #define NGINX_VER          "nginx"
[root@server1 nginx-1.12.0]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src

[root@server1 nginx-1.12.0]# ./configure --prefix=/usr/local/lnmp/nginx --user=nginx --group=nginx --with-threads --with-file-aio --with-http_ssl_module --with-http_stub_status_module


[root@server1 nginx-1.12.0]# make && make install


[root@server1 nginx-1.12.0]# useradd -M -d /usr/local/lnmp/nginx -s /sbin/nologin  -u 800 nginx
[root@server1 nginx-1.12.0]# id nginx
uid=800(nginx) gid=800(nginx) groups=800(nginx)
[root@server1 sbin]# ln -s /usr/local/lnmp/nginx/sbin/nginx  /sbin/
[root@server1 sbin]# ./nginx
[root@server1 sbin]# netstat -antlp
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      7059/nginx          
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      885/sshd            
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      961/master          
tcp        0      0 172.25.66.1:22              172.25.66.250:37162         ESTABLISHED 1717/sshd           
tcp        0      0 172.25.66.1:22              172.25.66.250:37157         ESTABLISHED 1676/sshd           
tcp        0      0 :::22                       :::*                        LISTEN      885/sshd            
tcp        0      0 ::1:25                      :::*                        LISTEN      961/master          
[root@server1 sbin]# curl localhost -I
HTTP/1.1 200 OK
Server: nginx                ##未显示具体版本
Date: Thu, 20 Jul 2017 05:45:07 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 20 Jul 2017 05:32:16 GMT
Connection: keep-alive
ETag: "59704060-264"

Accept-Ranges: bytes


三.实验
1.nginx虚拟主机定义
[root@server1 sbin]# cd /usr/local/lnmp/nginx/conf/
[root@server1 conf]# vim nginx.conf
116 server {
117         listen 80;                ##监听80端口
118         server_name www.westos.org;        ##访问域名
119         location / {            ##对URL进行匹配
120                 root /web1;            ##访问路径
121                 index index.html;        ##首页文件,按顺序匹配
122         }
123 }
124 }
[root@server1 conf]# nginx -t            ##检测配置文件是否有语法错误
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful
[root@server1 conf]# nginx -s reload        ##修改配置文件后重新加载才会使其立即生效
[root@server1 conf]# mkdir  /web1        ##建立访问路径,编写访问内容
[root@server1 conf]# vim /web1/index.html
[root@server1 conf]# cat /web1/index.html
<h1>www.westos.org</h1>

测试:





2.https加密 证书访问
https时用的是443端口,配置前要确定安装的openssl和openssl-devel。采用https的服务器必须从CA申请一个用于证明服务器用途类型的证书,服务器与客户端之间的传输是加密的,必须使用证书访问
[root@server1 conf]# cd /etc/pki/tls/certs/
[root@server1 certs]# make cert.pem    ##产生证书和秘钥,用该命令将证书和key生成在一个文件里
umask 77 ; \
    PEM1=`/bin/mktemp /tmp/openssl.XXXXXX` ; \
    PEM2=`/bin/mktemp /tmp/openssl.XXXXXX` ; \
    /usr/bin/openssl req -utf8 -newkey rsa:2048 -keyout $PEM1 -nodes -x509 -days 365 -out $PEM2 -set_serial 0 ; \
    cat $PEM1 >  cert.pem ; \
    echo ""    >> cert.pem ; \
    cat $PEM2 >> cert.pem ; \
    rm -f $PEM1 $PEM2
Generating a 2048 bit RSA private key
....................................+++
.........................+++
writing new private key to '/tmp/openssl.KtaXfU'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:shaanxi
Locality Name (eg, city) [Default City]:xi'an
Organization Name (eg, company) [Default Company Ltd]:westos
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:server1
Email Address []:674211605@qq.com
[root@server1 certs]# mv cert.pem /usr/local/lnmp/nginx/conf/    ##将生成的key移动至nginx的默认目录
[root@server1 certs]# cd -
/usr/local/lnmp/nginx/conf
[root@server1 conf]# vim nginx.conf
ssl_certifate cert.pem;

ssl_certifate_key cert.pem;


[root@server1 conf]#  nginx -t
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful
[root@server1 conf]# nginx -s reload
测试:

浏览器搜索http://172.25.66.1 显示nginx默认页面





浏览器搜索https://172.25.66.1 加密后的页面,通过下载证书访问指定页面





3.监控连接数
使用在源码编译时加入的--with-http_stub_status_module模块
[root@server1 conf]# vim nginx.conf
 48         location /status {        ##/status表示监控模块
 49                 stub_status on;
 50                 access_log off;    
 51                 allow 127.0.0.1;    ##允许本地访问
 52                 deny all;        ##拒绝其他所有

 53         }


[root@server1 conf]#  nginx -t
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful
[root@server1 conf]# nginx -s reload

测试:

在其他主机搜索172.25.66.1/status(配置文件设置该主机无法访问禁止访问)



在本机测试:
[root@server1 conf]# curl localhost/status
Active connections: 1
server accepts handled requests
 10 10 15

Reading: 0 Writing: 1 Waiting: 0






4.网页重写
当访问www.westos.org是重写为https://www.wstos.org
[root@server1 conf]# vim nginx.conf
117         location / {
118             root   /web1;
119             index  index.html index.htm;
120         }
121     }
122 server {
123         listen 80;
124         server_name www.westos.org;
125         rewrite ^(.*)$ https://www.westos.org permanent;
##将输入的url重定向为https://www.westos.org,permanent表示永久重定向,也可用redirect表示临时重定向
126
127 }

128 }


[root@server1 conf]#  nginx -t
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful

[root@server1 conf]# nginx -s reload



测试:
[root@server1 conf]# curl www.westos.org -I
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Thu, 20 Jul 2017 07:33:18 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive

Location: https://www.westos.org







5.负载均衡
5.1
[root@server2 ~]# vim /var/www/html/index.html
[root@server2 ~]# cat /var/www/html/index.html        ##编辑网页显示内容,以便于区分server2和server3
<h1>server2-www.westos.org</h1>
[root@server2 ~]# /etc/init.d/httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 172.25.6.2 for ServerName
                                                           [  OK  ]
[root@server3 ~]# vim /etc/httpd/conf/httpd.conf    ##为了实验效果,将server3的http服务的监听端口改为8080
136 Listen 8080
[root@server3 ~]# vim /var/www/html/index.html
[root@server3 ~]# cat /var/www/html/index.html        ##编辑网页显示内容,以便于区分server2和server3
<h1>server3-www.westos.org</h1>
[root@server3 ~]# /etc/init.d/httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 172.25.6.3 for ServerName
                                                           [  OK  ]
[root@server1 conf]# vim nginx.conf
 17 http {
 18         upstream westos {        ##westos是该模块的一个别名
 19         server 172.25.66.2:80;    ##访问后端服务的80端口    
 20         server 172.25.66.3:8080;    ##访问后端服务的8080端口
 21         }
126 server {
127         listen 80;
128         server_name www.westos.org;
129         #rewrite ^(.*)$ https://www.westos.org permanent;
130         location / {
131                 proxy_pass http://westos;##轮询
132         }
133 }

134 }


[root@server1 conf]#  nginx -t
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful
[root@server1 conf]# nginx -s reload

测试:

使用server2和server3测试:(server2和server3实现轮询)






5.2
[root@server1 conf]# vim /etc/httpd/conf/httpd.conf
136 Listen 8000
[root@server1 conf]# vim /var/www/html/index.html
[root@server1 conf]# cat /var/www/html/index.html
<h1>当前网站正在维护..........</h1>
[root@server1 conf]# /etc/init.d/httpd restart
Stopping httpd:                                            [FAILED]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 172.25.66.1 for ServerName
[root@server1 conf]# vim nginx.conf
17 http {
 18         upstream westos {
 19
 20         server 172.25.66.2:80 ;
 21         server 172.25.66.3:8080;
 22         server 127.0.0.1:8000 backup;
##当server1和server2都不能正常工作时,就会访问本地服务器的8000端口
 23         }
                                

测试:
当三台主机http服务都开启时:当访问www.westos.org时,在server2和server3实现负载均衡
[root@server1 conf]# cat /var/www/html/index.html
<h1>当前网站正在维护..........</h1>
[root@server1 conf]# for i in {1..10}; do curl www.westos.org ; done
<h1>server2-www.westos.org</h1>
<h1>server3-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server3-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server3-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server3-www.westos.org</h1>
<h1>server2-www.westos.org</h1>

<h1>server3-www.westos.org</h1>


当server2和server3http服务停止时,server1http服务开启时:当访问www.westos.org时,会访问server1的8000端口



[root@server2 ~]# /etc/init.d/httpd stop
Stopping httpd:                                            [  OK  ]
[root@server3 ~]# /etc/init.d/httpd stop
Stopping httpd:                                            [  OK  ]
[root@server1 conf]# for i in {1..10}; do curl www.westos.org ; done
<h1>当前网站正在维护..........</h1>
<h1>当前网站正在维护..........</h1>
<h1>当前网站正在维护..........</h1>
<h1>当前网站正在维护..........</h1>
<h1>当前网站正在维护..........</h1>
<h1>当前网站正在维护..........</h1>
<h1>当前网站正在维护..........</h1>
<h1>当前网站正在维护..........</h1>
<h1>当前网站正在维护..........</h1>

<h1>当前网站正在维护..........</h1>





5.3权重
[root@server1 conf]# vim nginx.conf
[root@server1 conf]# vim nginx.conf
17 http {
 18         upstream westos {
 19
 20         server 172.25.66.2:80 weight=2 ;
 21         server 172.25.66.3:8080;

 22         server 127.0.0.1:8000 backup;


[root@server1 conf]#  nginx -t
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful
[root@server1 conf]# nginx -s reload

测试:
[root@server1 conf]# for i in {1..10}; do curl www.westos.org ; done
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server3-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server3-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server3-www.westos.org</h1>

<h1>server2-www.westos.org</h1>






6.ip_haxi
来源为同一个ip时只会访问该主机第一次访问的服务器,不支持backup
[root@server1 conf]# vim nginx.conf
17 http {
 18         upstream westos {
 19         ip_hash;
 20         server 172.25.66.2:80 ;
 21         server 172.25.66.3:8080;
 22         #server 127.0.0.1:8000 backup;
 23         }

[root@server1 conf]#  nginx -t
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful
[root@server1 conf]# nginx -s reload
[root@server1 conf]# for i in {1..10}; do curl www.westos.org ; done
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>
<h1>server2-www.westos.org</h1>

<h1>server2-www.westos.org</h1>



7.nginx绑定cpu
[root@server1 ~]# cd /usr/local/lnmp/nginx/conf/
[root@server1 conf]# vim nginx.conf
  3 worker_processes  2;        ##开启两个nginx进程
  4 work_cpu_affinity 01 10;        ##第一个nginx进程对应第一个cpu内核,第二个nginx进程对应第二个cpu内核
 10
 11
 12 events {
 13     worker_connections  65535;    ##允许可连接进程的最大数
 14 }
[root@server1 conf]# nginx  -t
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful
[root@server1 conf]# nginx -s reload

[root@server1 conf]# vim /etc/security/limits.conf    ##必须在文件更改配置才会生效
# End of file
nginx  -  nofile        65535
[root@server1 conf]# usermod -s /bin/bash nginx        ##给nginx用户改为交互式用户
[root@server1 conf]# su - nginx
-bash-4.1$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7820
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65535        ##生效
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1024
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
-bash-4.1$ logout
[root@server1 conf]# sysctl -a | grep file        ##sysctl -a显示所有的系统参数
fs.file-nr = 448    0    98865
fs.file-max = 98865
 




原创粉丝点击