Nginx服务

98 阅读7分钟

Nginx概述

  • Nginx是一个高性能的HTTP和反向代理服务器。
  • 是一款轻量级的高性能的web服务器/反向代理服务器/电子邮件(IMAP/POP3)代理服务器
  • 单台物理服务器可支持30 000~50 000个并发请求。
  • 轻量级,同样起web服务,比apache占用更少的内存及资源
  • 抗并发,nginx处理请求是异步非阻塞的,而apache是阻塞型的在高并发下,nginx能保持低资源低消耗高性能
  • 高度模块化的设计,编写模块相对简

Nginx和Apache最核心的区别

apache是同步多进程模型,一个连接对应一个进程,nginx是异步的,多个连接可以对应一个进程。

Nginx处理静态文件好,耗费内存少,只适合静态和反向。

Apache在处理动态有优势,

nginx并发性比较好,CPU占用内存低,如果rewrite频繁,选用apache最佳。

安装Nginx 服务

[root@localhost ~]# systemctl stop firewalld
[root@localhost ~]# systemctl disable firewalld
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@localhost ~]# setenforce 0

```js

image.png

安装依赖包

yum -y install pcre-devel zlib-devel gcc gcc-c++ make

useradd -M -s /sbin/nologin/ nginx

将安装nginx所需的软件包传到/opt目录下并解压

[root@localhost opt]# ls
rh
[root@localhost opt]# rz -E
rz waiting to receive.
[root@localhost opt]# ls
nginx-1.12.0.tar.gz  rh
[root@localhost opt]# tar zxvf nginx-1.12.0.tar.gz -C /opt/
nginx-1.12.0/

image.png

编译安装Nginx

[root@localhost opt]# ls
nginx-1.12.0  nginx-1.12.0.tar.gz  rh
[root@localhost opt]# cd nginx-1.12.0/
[root@localhost nginx-1.12.0]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@localhost nginx-1.12.0]# ./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
> --with-http_stub_status_module

```js

image.png

编译安装及优化路径

make && make install

ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/

Nginx开启及关闭

image.png image.png

添加nginx服务

vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx 
After=network.target
[Service]
Type=forking 
PIDFile=/usr/local/nginx/logs/nginx.pid 
ExecStart=/usr/local/nginx/sbin/nginx 
ExecReload=/bin/kill -s HUP $MAINPID 
ExecStop=/bin/kill -s QUIT $MAINPID 
PrivateTmp=true
[Install]
WantedBy=multi-user.target
-----------------------------------------------------------
[Unit]:服务的说明
Description:描述服务
After:依赖,当依赖的服务启动之后再启动自定义的服务
[Service]服务运行参数的设置
Type=forking是后台运行的形式,使用此启动类型应同时指定PIDFile=,以便systemd能够跟踪服务的主进程。
ExecStart为服务的具体运行命令
ExecReload为重启命令
ExecStop为停止命令
Privatermp=True表示给服务分配独立的临时空间
注意:启动、重启、停止命令全部要求使用绝对路径
 
[Install]服务安装的相关设置,可设置为多用户

```js

image.png image.png

认识Nginx服务的主配置文件 nginx.conf

vim /usr/local/nginx/conf/nginx.conf

全局块:全局配置,对全局生效;

events块:配置影响Nginx服务器与用户的网络连接;

http块:配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置;

server块:配置虚拟主机的相关参数,一个http块中可以有多个server块;

location块:用于配置匹配的uri;

upstream:配置后端服务器具体地址,负载均衡配置不可或缺的部分;

全局配置

image.png

image.png

I/O事件配置

image.png

内核优化

vim /etc/security/limits.conf

image.png image.png

image.png

HTTP设置

http {
	##文件扩展名与文件类型映射表
    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"';
 
	##访问日志位置
    #access_log  logs/access.log  main;
 
	##开启文件传输模式
    sendfile        on;
 	##减少网络报文段的数量
    #tcp_nopush     on;
 
	##连接保持超时时间,单位是秒
    #keepalive_timeout  0;  #不开启长连接
    keepalive_timeout  65;
 
	##gzip模块设置,设置是否开启gzip压缩输出
    #gzip  on;
 
##Web 服务的监听配置
server {
	##监听地址及端口
	listen 80; 
	##站点域名,可以有多个,用空格隔开
	server_name localhost;
 
	##网页的默认字符集
	charset utf-8;
 
	##根目录配置
	location / {
	
		##网站根目录的位置/usr/local/nginx/html
		root html;
	
		##默认首页文件名
		index index.html index.htm;
	}
 
	##内部错误的反馈页面
	error_page 500 502 503 504 /50x.html;
	##错误页面配置
	location = /50x.html {
		root html;
	}
}
}
-----------------------------------------------------------------------------------------------
日志格式设定:
$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;
$remote_user:用来记录客户端用户名称;
$time_local:用来记录访问时间与时区;
$request:用来记录请求的url与http协议;
$status:用来记录请求状态;成功是200,
$body_bytes_sent:记录发送给客户端文件主体内容大小;
$http_referer:用来记录从哪个页面链接访问过来的;
$http_user_agent:记录客户浏览器的相关信息;
通常web服务器放在反向代理的后面,这样就不能获取到客户的p地址了,通过$remote_add拿到的Ip地是反向代理服务器的ip地址。
反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。
 
location常见配置指令,root、alias、proxy_pass 
root、alias不能同时配置
root(根路径配置):root  /var/www/html   请求www.stevelu.com/test/1.html,会返回文件/var/www/html/test/1.html 
alias(别名配置):alias   /var/www/html   请求www.stevelu.com/test/1.html,会返回文件/var/www/html/1.html 
proxy pass(反向代理配置)

```js

image.png

查看网页

image.png

image.png

image.png

root (根)

第一种情况 如果访问http://192.168.52.110/my/test/test.html 访问的路径为:/usr/local/nginx/html/my/test/test.html image.png 第二种情况 如果访问http://192.168.52.110/my/test/test.html 访问的路径为:/usr/local/nginx/html/my/test/test.html image.png image.png image.png

alias(别名)

[root@localhost ~]# cd /var/www/html
[root@localhost html]# ls
[root@localhost html]# echo "this is var" > test.html
[root@localhost html]# ls
test.html
[root@localhost html]# cat test.html 
this is var 
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
------------------------------------------------------------------ 
location /test {
            alias   /var/www/html;
            index  index.html index.htm;
        }
[root@localhost html]# nginx -t  #检查语法
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost html]# systemctl restart nginx #重启服务

```js

image.png

image.png image.png

image.png image.png

image.png image.png

访问状态统计配置

/usr/local/nginx/sbin/nginx -V

image.png image.png cat /opt/nginx-1.12.0/auto/options I grep YES
#可查看nginx已安装的所有模块

[root@localhost ~]#cd /usr/local/nginx/conf
[root@localhost conf]# ls
fastcgi.conf          fastcgi_params.default  mime.types          nginx.conf.default   uwsgi_params
fastcgi.conf.default  koi-utf                 mime.types.default  scgi_params          uwsgi_params.default
fastcgi_params        koi-win                 nginx.conf          scgi_params.default  win-utf
[root@localhost conf]# cp nginx.conf nginx.conf.bak #备份配置文件 以防配置出错
    vim /usr/local/nginx/conf/nginx.conf
    ......
    http {
    ......
     server {
      listen 80;
      server_name localhost;
      charset utf-8;
      location / {
		root html;
		index index.html index.htm;
	  }
-----------------------------------------------------------
      ##添加 stub_status 配置##
      location /status {      #访问位置为/status
       stub_status on;        #打开状态统计功能
       access_log off;        #关闭此位置的日志记录
      }
    }
  }
[root@localhost conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost conf]# systemctl restart nginx

```js

image.png

重启服务,访问测试 image.png 浏览器访问 http://192.168.52.110/status Active connections :表示当前的活动连接数; server accepts handled requests :表示已经处理的连接信息,三个数字依次表示已处理的连接数、成功的TCP握手次数、 已处理的请求数。

image.png image.png

```vim 1.sh
-------------------------------------------------------
#!/bin/bash
con=`curl -Ls http://192.168.239.10/status | awk 'NR==1{print $3}'`
if [ $con -gt 20000 ]
then
echo "当前并发数量为 $con ,超过预警值"
fi

```js

基于授权的访问控制

1、生成用户密码认证文件

[root@localhost nginx]# pwd
/usr/local/nginx
[root@localhost nginx]# yum install httpd-tools -y
[root@localhost nginx]# htpasswd -c ./usrlist.txt my
New password: 
Re-type new password: 
Adding password for user my
[root@localhost nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  usrlist.txt  uwsgi_temp
[root@localhost nginx]# cat usrlist.txt 
my:$apr1$S9xb3mEi$y/2OiJE58zFme0huBGJ6S/
[root@localhost nginx]# htpasswd ./usrlist.txt qyd
New password: 
Re-type new password: 
Adding password for user qyd
[root@localhost nginx]# cat usrlist.txt 
my:$apr1$S9xb3mEi$y/2OiJE58zFme0huBGJ6S/
qyd:$apr1$wBueVUlF$NOd6jD46F.w.ulqxrE06M/
[root@localhost nginx]# ll
总用量 8
drwx------. 2 nginx root    6 510 16:29 client_body_temp
drwxr-xr-x. 2 root  root 4096 510 21:53 conf
drwx------. 2 nginx root    6 510 16:29 fastcgi_temp
drwxr-xr-x. 3 root  root   52 510 20:47 html
drwxr-xr-x. 2 root  root   58 510 21:54 logs
drwx------. 2 nginx root    6 510 16:29 proxy_temp
drwxr-xr-x. 2 root  root   19 510 16:20 sbin
drwx------. 2 nginx root    6 510 16:29 scgi_temp
-rw-r--r--. 1 root  root   83 510 22:11 usrlist.txt
drwx------. 2 nginx root    6 510 16:29 uwsgi_temp
[root@localhost nginx]# chown nginx usrlist.txt 
[root@localhost nginx]# chmod 400 usrlist.txt 
[root@localhost nginx]# ll
总用量 8
drwx------. 2 nginx root    6 510 16:29 client_body_temp
drwxr-xr-x. 2 root  root 4096 510 21:53 conf
drwx------. 2 nginx root    6 510 16:29 fastcgi_temp
drwxr-xr-x. 3 root  root   52 510 20:47 html
drwxr-xr-x. 2 root  root   58 510 21:54 logs
drwx------. 2 nginx root    6 510 16:29 proxy_temp
drwxr-xr-x. 2 root  root   19 510 16:20 sbin
drwx------. 2 nginx root    6 510 16:29 scgi_temp
-r--------. 1 nginx root   83 510 22:11 usrlist.txt
drwx------. 2 nginx root    6 510 16:29 uwsgi_temp

```js

image.png image.png 2、修改主配置文件相对应目录,添加认证配置项

vim /usr/local/nginx/conf/nginx.conf

 location /test {
            alias  /var/www/html;
            index  index.html index.htm;
            auth_basic "Hello everyone";
            auth_basic_user_file /usr/local/nginx/usrlist.txt;
        }
        
```js

image.png

3、重启服务,访问测试

nginx -t systemctl restart nginx 浏览器访问

image.png

基于客户端的访问控制

Nginx 基于客户端的访问控制规则如下:

  • deny IP/IP 段:拒绝某个IP或I 段的客户端访问。
  • allow IP/IP 段:允许某个IP或IP段的客户端访问。
  • 规则从上往下执行,如匹配则停止,不再往下匹配。
vim /usr/local/nginx/conf/nginx.conf
 
 location /test {
            alias  /var/www/html;
            index  index.html index.htm;
            auth_basic "Hello everyone";
            auth_basic_user_file /usr/local/nginx/usrlist.txt;
            deny 192.168.52.110;
        }

```js

image.png 重启服务 ,访问测试 systemctl restart nginx

image.png

image.png

基于虚拟主机

虚拟主机有三种:基于域名、基于IP、基于端口

1、为虚拟主机提供域名解析

[root@localhost ~]# vim /etc/hosts
----------------------------------------------------------------------------------
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.52.110  www.my.com www.qyd.com

image.png 2、为虚拟主机准备网页文档

[root@localhost html]# ls
test.html
[root@localhost html]# mkdir my qyd
[root@localhost html]# ls
my  qyd  test.html
[root@localhost html]# echo "this is my test web" > my/index.html
[root@localhost html]# echo "this is qyd test web" > qyd/index.html

```js

image.png 3、修改Nginx配置文件

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# ls
fastcgi.conf          fastcgi_params.default  mime.types          nginx.conf.bak      scgi_params.default   win-utf
fastcgi.conf.default  koi-utf                 mime.types.default  nginx.conf.default  uwsgi_params
fastcgi_params        koi-win                 nginx.conf          scgi_params         uwsgi_params.default
[root@localhost conf]# cp nginx.conf.default nginx.conf   #还原默认的配置文件
cp:是否覆盖"nginx.conf"? y
 
----------------------------------------------------------------
 server {
        listen       80;
        server_name  www.my.com;
 
        charset utf-8;
 
        access_log  logs/my.com.access.log;
 
        location / {
            root   /var/www/html/my;
            index  index.html index.htm;
        }
 
        #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;
        }
 
server {
          listen       80;
          server_name  www.qyd.com;
 
          charset utf-8;
 
          access_log  logs/qyd.com.access.log;
 
          location / {
              root   /var/www/html/qyd;
              index  index.html index.htm;
          }
 
          #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;
          }
     }
     
```js

image.png

image.png

重启服务 ,输入域名进行测试

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

```js

image.png

基于IP的Nginx虚拟主机

1、设置虚拟IP

[root@localhost ~]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.52.110  netmask 255.255.255.0  broadcast 192.168.52.255
        inet6 fe80::d6fa:c8c:b90d:12db  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:e6:f0:79  txqueuelen 1000  (Ethernet)
        RX packets 85179  bytes 76908377 (73.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 38826  bytes 9886685 (9.4 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
 
ens33:0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.52.11  netmask 255.255.255.0  broadcast 192.168.52.255
        ether 00:0c:29:e6:f0:79  txqueuelen 1000  (Ethernet)

```js

image.png 2、编辑配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
--------------------------------------------------------------
 server {
        listen       192.168.52.110:80;
        server_name  www.my.com;
 
        charset utf-8;
 
        access_log  logs/my.com.access.log;
 
        location / {
            root   /var/www/html/my;
            index  index.html index.htm;
        }
 
        #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;
        }
 
server {
          listen       192.168.52.11:80;
          server_name  www.qyd.com;
 
          charset utf-8;
 
          access_log  logs/qyd.com.access.log;
 
          location / {
              root   /var/www/html/qyd;
              index  index.html index.htm;
          }
 
          #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;
          }
     }
     
```js

image.png image.png 3、重启并测试

image.png

基于端口的Nginx虚拟主机

1、修改配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
---------------------------------------------------------------
 server {
        listen       192.168.52.110:330;
        server_name  www.my.com;
 
        charset utf-8;
 
        access_log  logs/my.com.access.log;
 
        location / {
            root   /var/www/html/my;
            index  index.html index.htm;
        }
 
        #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;
        }
 
   server {
          listen       192.168.52.110:30;
          server_name  www.qyd.com;
 
          charset utf-8;
 
          access_log  logs/qyd.com.access.log;
 
          location / {
              root   /var/www/html/qyd;
              index  index.html index.htm;
          }
 
          #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;
          }
     }
     
```js

image.png image.png 2、重启并测试

image.png