Nginx的搭建和优化

一. Nginx简介

1.1 概述

Nginx:

  • Nginx 是一个高性能的HTTP和反向代理服务器。
  • 是一款轻量级的高性能的web服务器/反向代理服务器/电子邮件(IMAP/POP3)代理服务器
  • 单台物理服务器可支持30 000~50 000个并发请求。

Apache:
Apache是以进程为基础的结构,进程要比线程消耗更多的系统开支,不太适用于多处理器环境,因此,在一个apache Web站点扩容时,通常是增加服务器或扩充群集节点而不是增加处理器。

1.2 Nginx和Apache优缺点比较

(1) Nginx相对于Apache的优点

  • 轻量级,同样是web服务,比 Apache 占用更少的内存及资源
  • 高并发,Nginx 处理请求是异步非阻塞的,而Apache则是同步阻塞的,在高并发下 Nginx 能保持低资源低消耗高性能;高度模块化的设计
  • 编写模块相对简单;社区活跃,各种高性能模块出品迅速

(2) Apache相对于Nginx的优点:

  • rewrite,比 Nginx 的 rewrite 更加强大;
  • 模块超多,基本想到的都可以找到;
  • 少bug,Nginx 的 bug 相对较多;
  • 超稳定

存在的理由:一般来说,需要性能的 web 服务,用Nginx。如果不需要性能只求稳定,那就用Apache。Nginx处理动态请求是弱项,一般动态请求要Apache去做,Nginx只适处理静态网页或反向代理

二. Nginx编译安装步骤

1 关闭防火墙,安装依赖包

# 关闭防火墙
[root@666 opt]# systemctl stop firewalld
[root@666 opt]# systemctl disable firewalld
[root@666 opt]# setenforce 0

#安装依赖包
[root@666 opt]# yum -y install pcre-devel zlib-devel openssl-devel gcc gcc-c++ make

2. 创建运行用户和组

#(Nginx服务程序默认以 nobody 身份运行,建议为其创建专门的用户账户,以便更精准的控制其访问权限)
[root@666 opt]# useradd -M -s /sbin/nologin nginx

3. 编译安装 Nginx

#切换至opt目录,将下载好的压缩包进行解压
cd /opt
[root@666 opt]# tar xf nginx-1.24.0.tar.gz 

#切换至解压后的文件夹编译
[root@666 opt]# cd nginx-1.24.0/
[root@666 nginx-1.24.0]# ./configure \
> --prefix=/usr/local/nginx \ #指定用户的安装路径
> --user=nginx \              #指定用户名
> --group=nginx \		      #指定组名
> --with-http_stub_status_module #启用 http_stub_status_module模块以支持状态统计

#编译安装
make -j4 && make install

4. 做软连接并启动nginx

#做软连接,让系统识别nginx的操作命令
[root@666 nginx-1.24.0]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/

#检查配置文件是否配置正确
[root@666 nginx-1.24.0]# nginx -t

#启动 nginx
[root@666 nginx-1.24.0]# nginx

#查看是否启动成功
[root@666 nginx-1.24.0]# netstat -lntp | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      12777/nginx: master

在这里插入图片描述

5. 停止Nginx

# 查看 nginx 进程号
[root@666 nginx-1.24.0]# cat /usr/local/nginx/logs/nginx.pid 
12777

#直接杀死
[root@666 nginx-1.24.0]# kill -3 12777
#查看此时进程就已经杀死了
[root@666 nginx-1.24.0]# ss -natp | grep nginx

#一定要杀父进程,杀死子进程是没用的
kill <pid>       根据进程号杀死进程
killall <进程名>  根据进程名杀死进程
pkill <关键词>    根据关键词杀死进程

6. 添加nginx系统服务

方法一:编写脚本

[root@666 nginx-1.24.0]# vim /etc/init.d/nginx

#!/bin/bash
#chkconfig: 35 99 20
#des:Nginx Service Control Script

COM="/usr/local/nginx/sbin/nginx"
PID="/usr/local/nginx/logs/nginx.pid"

case "$1" in
start)
        netstat -lntp | grep nginx
        if [ $? -eq 0 ]
        then
                echo "Nginx 已经启动"
        else
                echo "Nginx 正在启动"
                $COM
        fi
;;

stop)
        kill -3 $(cat $PID)
;;

restart)
        $0 stop
        $0 start
;;

reload)
        kill -s HUP $(cat $PID)
;;

status)
        netstat -lntp | grep nginx
        if [ $? -eq 0 ]
        then
                echo "Nginx 服务已开启"
        else
                echo "Nginx 服务未开启"
        fi
;;

*)
	 echo "请输入正确格式:$0 (start | stop | restart | status | reload)"
esac

# 执行脚本
[root@666 init.d]# chmod +x /etc/init.d/nginx 
[root@666 init.d]# chkconfig --add nginx
[root@666 init.d]# chkconfig --list nginx

#启动服务
[root@666 init.d]# service  nginx start 

#关闭服务
[root@666 init.d]# service  nginx stop 

方法二 将nginx命令加入服务

[root@666 init.d]# cd /lib/systemd/system
[root@666 system]# vim nginx.serivce

#!/bin/bash

[Unit]
After=network.target

[Service]
Type=forking
PIDFile =/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecrReload=/bin/kill -s HUP $MAINPID
ExecrStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true


[Install]
WantedBy=multi-user.target



##磁盘上的ngin服务更改,运行'systemctl daemon-reload'重新加载单元。
[root@666 system]# systemctl daemon-reload 
[root@666 system]# systemctl status nginx.service 

7. 查看nginx版本信息

[root@666 system]# nginx -v
nginx version: nginx/1.24.0

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

[root@666 system]# vim /usr/local/nginx/conf/nginx.conf

1、全局块:全局配置,对全局生效;
2、events块:配置影响Nginx服务器与用户的网络连接;
3、http块:配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置;
4、server块:配置虚拟主机的相关参数,一个http 块中可以有多个server块;
5、location块:用于配置匹配的 uri;
6、upstream:配置后端服务器具体地址,负载均衡配置不可或缺的部分。

全局配置

#user nobody;			      	#运行用户,若编译时未指定则默认为nobody
worker_processes 1;			  	#工作进程数量,一般设置为和cPu核数一样;设置为auto,nginx将会自己获取这个数值
#error_log logs/error.log;		#错误曰志文件的位置
#pid logs/ nginx.pid;			#PID 文件的位置
worker_rlinit_nofile 60000;		#设置所有worker进程最大可以打开的文件数,默认为1024

I/O事件配置

events {
    
    
	use epoll;					#使用epoll I/o模型,2.6及以上版本的系统内核,建议使用epoll模型以提高性能
	worker_connections 60000 ;	#每个进程处理60000个连接
	multi_accept on;			#是否一次性将监听到的连接全接收进来,默认为off,关闭时一次接收一条连接
	accept_mutex on;			#默认为on,开启时表示以串行方式接入新连接,否则将通报给所有worker。这可能会浪费资源并产生不可预计的后果,例如惊群问题
}

epoll(socket描述符)是Linux内核]为处理大批量文件描述符而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著提高程序在大量并发连接中只有少量活跃的情况下的系统CPU利用率

若工作进程数为 8,每个进程处理 4 096 个连接,则允许 Nginx 正常提供服务的连接数 已超过 3 万个(4 096×8=32 768),当然具体还要看服务器硬件、网络带宽等物理条件的性 能表现。

  1. 如提高每个进程的连接数还需执行"ulimit -n 65535"命令临时修改本地每个进程可以同时打开的最大文件数。

  2. 在Linux平台.上,在进行高并发TCP连接处理时,最高的并发数量都要受到系统对用户单一进程同时可打开文件数量的限制(这是因为系统为每个TCP连接都要创建一个socket句柄,每个socket句柄同时也是一个文件句柄)。

  3. 可使用ulimit -a命令查看系统允许当前用户进程打开的文件数限制。

#查看系统允许当前用户进程打开的文件数
[root@666 system]# 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) 15603
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 15603
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

#临时修改本地每个进程可以同时打开的最大文件数
[root@666 system]# ulimit -n 60000
#查看修改后的
[root@666 system]# 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) 15603
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 60000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 15603
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

永久修改ulimit配置

[root@666 system]# vim /etc/security/limits.conf

在这里插入图片描述配置完重启即可生效

http配置

使用“http { }”界定标记,包括访问日志、HTTP 端口、网页目录、默认字符集、连接保 持,以及后面要讲到的虚拟 Web 主机、PHP 解析等一系列设置,其中大部分配置语句都包 含在子界定标记“server { }”内

http {
    
    
	##文件扩展名与文件类型映射表
	include mime. types;
	##默认文件类型
	default_type application/octet-stream;
	##日志格式设定
	#log_format main  	'Sremote addr - $remote user [$time local] "$request" '
	#					'$status $body_bytes_sent "$http referer" '
	#					'"$http user agent" "shttp x forwarded for"';
	##访问日志位置
	#access_log logs/access.logmain;
	##开启文件传输模式
	sendfile 		on; 
	#只在sendfile on时有效。调用tcp_cork方法,让数据包不会马上传送出去,等到数据包最大时,一次性的传输出去,这样有助于解决网络堵赛。默认为off。
	#tcp_nopush 	on;
	##连接保持超时时间,单位是秒
	#keepalive_timeout   0;
	keepalive_timeout   65;
	##gzip模块设置,设置是否开启gzip压缩输出
	#gzip  on;
	
	##web服务的监听配置
	server {
    
    
		##监听地址及端口
		listen 80;
		##站点域名,可以有多个,用空格隔开
		server_name www.kgc.com;
		##网页的默认字符集
		charset utf-8;
		##根目录配置
		location / {
    
    
			##网结根目录的位置/usr/local/nginx/html
			root html;
			##默认首页文件名
			index index.html index.php;
		}
		##内部错误的反馈页面
		error_page 500 502 503 504 /50x.html;
		##错误页面配置
		location = /50x.html {
    
    
			root html;
		}
	}
}

日志格式设定:
r e m o t e a d d r 与 remote_addr与 remoteaddrhttp_x_forwarded_for用以记录客户端的ip地址;
$remote_user:用来记录客户端用户名称;
$time_local:用来记录访问时间与时区;
$request:用来记录请求的uri与http协议;
$status:用来记录请求状态,成功是200;
$body_bytes_sent :记录发送给客户端文件主体内容大小;
$http_referer:用来记录从哪个页面链接访问过来的;
h t t p u s e r a g e n t : 记录客户浏览器的相关信息 ; 通常 w e b 服务器放在反向代理的后面,这样就不能获取到客户的 I P 地址了,通过 http_user_agent:记录客户浏览器的相关信息; 通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过 httpuseragent:记录客户浏览器的相关信息;通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过remote _add拿到的IP地址是反向代理服务器的ip地址。反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。

$remote_addr记录的是上一层节点的地址
$http_x_forwarded_for 记录所有经过节点的地址

location常见配置指令,root、 alias、 proxy_pass
root(根路径配置) : root /var/www/html
请求www.kgc.com/test/1.html,会返回文件/var/www/html/test/1.html
alias (别名配置) : alias /var/www/html
请求www.kgc.com/test/1.html,会返回文件/var/www/html/1.html
proxy _pass(反向代理配置〉

访问状态统计配置

  • nginx 内置了 HTTP_STUB_STATUS 状态统计模块,用来反馈当前的 Web 访问情况, 配置编译参数时可添加–with-http_stub_status_module 来启用此模块支持,可以使用命

  • 可以使用命令/usr/local/nginx/sbin/nginx –v 查看已安装的 Nginx 是否包含 HTTP_STUB_STATUS 模块。

  • 操作步骤:

    1. 修改 nginx.conf 配置文件,指定访问位置并添加 stub_status 配置(修改之前进行备份
#先拷贝一份配置文件
[root@localhost conf]#cp /usr/local/nginx/conf/nginx.conf nginx.conf.bak
 
#  修改 nginx.conf 配置文件
[root@localhost conf]#vim /usr/local/nginx/conf/nginx.conf
 
events {
    
    
    use epoll;
    worker_connections  1024;
}
 
    server {
    
    
        listen       80;
        server_name  www.yxp.com;
 
 
        charset utf-8;
      location / {
    
    
            root   html;
            index  index.html index.htm;
        }
 
        location /status {
    
      ##访问位置为/status
            stub_status on;  ##打开状态统计功能
            access_log off;  ##关闭此位置的日志记录
        }

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

编写shell脚本来判断监控服务器的并发量

在这里插入图片描述

四. 基于授权的访问控制

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

yum install -y httpd-tools
htpasswd -c /usr/local/nginx/passwd.db zhangsan
chown nginx /usr/local/nginx/passwd.db
chmod 400 /usr/local/nginx/passwd.db

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

vim /usr/local/nginx/conf/nginx.conf
......
	server {
    
    
		location / {
    
    
			......
			##添加认证配置##
			auth_basic "secret";				#设置密码提示框文字信息
			auth_basic_user_file /usr/local/nginx/passwd.db;
		}
	}

3.重启服务,访问测试
nginx -t
systemctl restart nginx

浏览器访问 http://192.168.137.102

-基于客户端的访问控制

访问控制规则如下:
deny IP/IP 段:拒绝某个 IP 或 IP 段的客户端访问。
allow IP/IP 段:允许某个 IP 或 IP 段的客户端访问。
规则从上往下执行,如匹配则停止,不再往下匹配。

vim /usr/local/nginx/conf/nginx.conf
......
	server {
    
    
		location / {
    
    
			......
			##添加控制规则##
			allow 192.168.80.200; 					#允许访问的客户端 IP
			deny all;								#拒绝其它IP客户端访问
		}
	}

systemctl restart nginx

基于域名的 Nginx 虚拟主机

1.为虚拟主机提供域名解析
echo "192.168.137.101 www.kgc.com www.benet.com" >> /etc/hosts

2.为虚拟主机准备网页文档
mkdir -p /var/www/html/benet
mkdir -p /var/www/html/kgc
echo "<h1>www.kgc.com</h1>" > /var/www/html/kgc/index.html
echo "<h1>www.benet.com</h1>" > /var/www/html/benet/index.html

3.修改Nginx的配置文件
vim /usr/local/nginx/conf/nginx.conf
......
http {
    
    
......
	server {
    
    
		listen 80;
		server_name www.kgc.com;					#设置域名www.kgc.com
		charset utf-8;
		access_log logs/www.kgc.access.log; 		#设置日志名
		location / {
    
    
			root /var/www/html/kgc;					#设置www.kgc.com 的工作目录
			index index.html index.php;
		}
		error_page 500 502 503 504 /50x.html;
		location = 50x.html{
    
    
			root html;
		}
	}
	
	server {
    
    
		listen 80;
		server_name www.benet.com;					#设置域名www.benet.com
		charset utf-8;
		access_log logs/www.benet.access.log; 
		location / {
    
    
			root /var/www/html/benet;
			index index.html index.php;
		}
		error_page 500 502 503 504 /50x.html;
		location = 50x.html{
    
    
			root html;
		}
	}	
}

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

浏览器访问
http://www.kgc.com
http://www.benet.com

基于IP 的 Nginx 虚拟主机

ifconfig ens33:0 192.168.137.120 netmask 255.255.255.0 

vim /usr/local/nginx/conf/nginx.conf
......
http {
    
    
......
	server {
    
    
		listen 192.168.137.102:80;					#设置监听地址192.168.80.10
		server_name www.kgc.com;
		charset utf-8;
		access_log logs/www.kgc.access.log; 
		location / {
    
    
			root /var/www/html/kgc;
			index index.html index.php;
		}
		error_page 500 502 503 504 /50x.html;
		location = 50x.html{
    
    
			root html;
		}
	}
	
	server {
    
    
		listen 192.168.137.120:80;					#设置监听地址192.168.80.11
		server_name www.benet.com;
		charset utf-8;
		access_log logs/www.benet.access.log; 
		location / {
    
    
			root /var/www/html/benet;
			index index.html index.php;
		}
		error_page 500 502 503 504 /50x.html;
		location = 50x.html{
    
    
			root html;
		}
	}	
}


systemctl restart nginx

浏览器访问
http://192.168.137.102
http://192.168.137.120

基于端口的 Nginx 虚拟主机

vim /usr/local/nginx/conf/nginx.conf
......
http {
    
    
......
	server {
    
    
		listen 192.168.137.102:8080;					#设置监听 8080 端口
		server_name www.kgc.com;
		charset utf-8;
		access_log logs/www.kgc.access.log; 
		location / {
    
    
			root /var/www/html/kgc;
			index index.html index.php;
		}
		error_page 500 502 503 504 /50x.html;
		location = 50x.html{
    
    
			root html;
		}
	}
	
	server {
    
    
		listen 192.168.137.102:8888;					#设置监听 8888 端口
		server_name www.benet.com;
		charset utf-8;
		access_log logs/www.benet.access.log; 
		location / {
    
    
			root /var/www/html/benet;
			index index.html index.php;
		}
		error_page 500 502 503 504 /50x.html;
		location = 50x.html{
    
    
			root html;
		}
	}	
}


systemctl restart nginx

浏览器访问
http://192.168.137.102:8080
http://192.168.137.102:8888

##Nginx 和 Apache 的差异:

轻量级,nginx比apache 占用更少的内存及资源;
静态处理,Nginx 静态处理性能比 Apache 高 ;
Nginx可以实现无缓存的反向代理加速,提高网站运行速度;
Nginx的性能和可伸缩性不依赖于硬件,Apache依赖于硬件;
Nginx支持热部署,启动速度迅速,可以在不间断服务的情况下,对软件版本或者配置进行升级;
nginx是异步进程,多个连接可以对应一个进程 ;apache是同步多进程,一个连接对应一个进程;
Nginx高度模块化,编写模块相对简单,且组件比Apache少
高并发下nginx 能保持低资源低消耗高性能;
Nginx 配置简洁, Apache配置复杂;

猜你喜欢

转载自blog.csdn.net/2302_76410765/article/details/130967351
今日推荐