nginx

nginx

Nginx epoll模型

1)epoll和select网络IO处理模型,
2)epoll异步网络IO模型,支持高并发。
3)select传统的网络IO模型,高并发能力弱。
4)Apache则使用的是传统的select模型,Nginx使用高并发的epoll模型

sendfile

传统文件传输:硬盘—>内核buf—>⽤户buf—>socket缓冲区(内核)—>协议引擎

sendfile文件传输:硬盘—>内核buf—>socket缓冲区(内核)—>协议引擎

nginx安装

yum安装

# 确认版本,关闭防火墙
# 初始化基本目录
[root@localhost:~]#  mkdir /soft/{code,logs,package,backup} -p
# 基础安装包
[root@localhost:~]#  yum install -y gcc gcc-c++ autoconf pcre pcre-devel make automake wget httpd-tools vim tree

# 配置官方yum源
[root@localhost:~]# vim /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
# 安装
[root@localhost:~]# yum install nginx -y
[root@localhost:~]# nginx -v
nginx version: nginx/1.24.0
# 查看编译参数
nginx -V
# 查看相关目录
[root@localhost:~]# rpm -ql nginx

nginx常用模块

image-20231118152615053

nginx内置变量

$uri: 当前请求的uri,不带参数 ⽐如访问:xx.com/url?name=wing 获取到 xx.com/url
$request_uri: 请求的uri,带完整参数 ⽐如访问:xx.com/url?name=wing 获取到 xx.com/url?
name=wing
$host: http请求报⽂中host⾸部,如果没有则以处理此请求的虚拟主机的主机名代替
$hostname: nginx服务运⾏在主机的主机名
$remote_addr: 客户端IP
$remote_port: 客户端端⼝
$remote_user: 使⽤⽤户认证时客户端⽤户输⼊的⽤户名
$request_filename: ⽤户请求中的URI经过本地root或alias转换后映射的本地⽂件路径
$request_method: 请求⽅法, GET POST PUT DELET
$server_addr: 服务器地址
$server_name: 服务器名称
$server_port: 服务器端⼝
$server_protocol: 服务器向客户端发送响应时的协议, 如http/1.1 http/1.0
$scheme:在请求中使⽤scheme, 如http://xxx.com中的http
$http_HEADER: 匹配请求报⽂中指定的HEADER
$http_host: 匹配请求报⽂中的host⾸部
$document_root: 当前请求映射到的root配置

nginx基本配置

nginx目录结构

[root@localhost:~]# rpm -ql nginx
/etc/logrotate.d/nginx # nginx日志切割配置(由logrotate,rsyslog工具负责切割的。)
/etc/nginx		# nginx配置文件目录
/etc/nginx/conf.d		# nginx主配置文件包含的目录(扩展名是xx.conf)
/etc/nginx/conf.d/default.conf # 默认的虚拟主机,包含一个或多个站点
/etc/nginx/fastcgi_params	# fastcgi参数,配合和PHP-fcgi联系配置
/etc/nginx/mime.types	# nginx所支持的文件类型
/etc/nginx/modules	# nginx模块路径,指向/usr/lib64/nginx/modules
/etc/nginx/nginx.conf	# nginx主配置文件
/etc/nginx/scgi_params	# (xxcgi是和动态程序交互的进程配置)
/etc/nginx/uwsgi_params	# uwsgi参数,配合动态服务Python配置
/usr/lib/systemd/system/nginx-debug.service	# systemd nginx debug方式命令启动文件
/usr/lib/systemd/system/nginx.service	# systemd nginx启动文件
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx		# nginx可执行程序文件,二进制命令(在任意地点,编译好带有【第三方模块】的命令,拷贝到这里用)
/usr/sbin/nginx-debug	# nginx可执行文件,nginx-debug方式启动(方便调试,所有错误日志都会打印)
/usr/share/doc/nginx-1.24.0
/usr/share/doc/nginx-1.24.0/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html	# 默认的站点目录
/usr/share/nginx/html/50x.html	# 报错5xx,重定向页面
/usr/share/nginx/html/index.html	# 默认的首页
/var/cache/nginx	# 缓存目录
/var/log/nginx		# 日志目录

nginx虚拟主机

配置基于域名虚拟主机

# 配置首页文件
[root@localhost:/etc/nginx/conf.d]# mkdir /soft/code/{www,bbs}
[root@localhost:/etc/nginx/conf.d]# echo "www.mononoke.top" > /soft/code/www/index.html
[root@localhost:/etc/nginx/conf.d]# echo "bbs.mononoke.top" > /soft/code/bbs/index.html
# 配置虚拟主机
[root@localhost:/etc/nginx/conf.d]#  cat {www,bbs}.conf
server {
    listen       80;
    server_name  www.mononoke.top;
    root /soft/code/www;
}
server {
    listen       80;
    server_name  bbs.mononoke.top;
    root /soft/code/bbs;
}

配置不同端口访问虚拟主机

[root@localhost:/etc/nginx/conf.d]# mkdir -p /soft/code/800{1..2}
[root@localhost:/etc/nginx/conf.d]# echo "8001" > /soft/code/8001/index.html
[root@localhost:/etc/nginx/conf.d]# echo "8002" > /soft/code/8002/index.html

[root@localhost:/etc/nginx/conf.d]# cat 800*
server {
 listen 8001;
 root /soft/code/8001;
 index index.html index.htm;
}
server {
 listen 8002;
 root /soft/code/8002;
 index index.html index.htm;
}
[root@localhost:/etc/nginx/conf.d]# nginx -t && systemctl reload nginx

[root@localhost:/etc/nginx/conf.d]# curl 192.168.79.130:8001
8001
[root@localhost:/etc/nginx/conf.d]# curl 192.168.79.130:8002
8002

配置虚拟主机别名

# 所谓虚拟主机别名,就是虚拟主机设置除了主域名以外的⼀个域名,实现⽤户访问的多个域名对应同⼀个虚拟主机⽹站的功能。
[root@localhost:/etc/nginx/conf.d]# cat www.conf 
server {
    listen       80;
    server_name  www.mononoke.top blog.mononoke.top;
    root /soft/code/www;
}
[root@localhost:/etc/nginx/conf.d]# nginx -t && systemctl reload nginx
[root@localhost:/etc/nginx/conf.d]# vim /etc/hosts
[root@localhost:/etc/nginx/conf.d]# curl www.mononoke.top
www.mononoke.top
[root@localhost:/etc/nginx/conf.d]# curl blog.mononoke.top
www.mononoke.top

nginx处理用户请求的逻辑

image-20231118165351970

nginx日志配置

http请求和返回

image-20231118165557264 image-20231118165522009

nginx日志规范

//配置语法: 包括: error.log access.log
Syntax: log_format name [escape=default|json] string ...;
Default: log_format combined "...";
Context: http
//Nginx默认配置
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
 '$status $body_bytes_sent "$http_referer" '
 '"$http_user_agent" "$http_x_forwarded_for"';
//Nginx⽇志变量
$remote_addr //表示客户端地址
$remote_user //http客户端请求nginx认证⽤户名
$time_local //Nginx的时间
$request //Request请求⾏, GET等⽅法、http协议版本
$status //respoence返回状态码
$body_bytes_sent //从服务端响应给客户端body信息⼤⼩
$http_referer //http上⼀级⻚⾯, 防盗链、⽤户⾏为分析
$http_user_agent //http头部信息, 客户端访问设备
$http_x_forwarded_for //http请求携带的http信息

stub_status状态监控

# stub_status
[root@localhost:/etc/nginx/conf.d]# cat nginx_status.conf 
server {
	listen 80;
	server_name nginxstatus.org;
	access_log off;
	root /soft/code/status;
	index index.html index.htm;
	
	location /nginx_status {
		stub_status;
        #来源IP限制
        #allow 127.0.0.1;           #允许指定的地址或地址段
        #deny all;                 #拒绝所有的地址
	}
}
image-20231118171035215

autoindex下载站点

Nginx默认是不允许列出整个目录浏览下载。

//autoindex常⽤参数
autoindex_exact_size off;
默认为on, 显示出⽂件的确切⼤⼩,单位是bytes。
修改为off,显示出⽂件的⼤概⼤⼩,单位是kB或者MB或者GB。

autoindex_localtime on;
默认为off,显示的⽂件时间为GMT时间。
修改为on, 显示的⽂件时间为⽂件的服务器时间。

charset utf-8,gbk;
默认中⽂⽬录乱码,添加上解决乱码。

[root@localhost:/etc/nginx/conf.d]# cat autoindex.conf 
server {
    listen 80;
    server_name autoindex.org;
    charset utf-8;
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;

    location / {
        root /var/log/nginx/;
	index index.html;
    }
}

limit访问限制

连接频率限制 limit_conn_module

请求频率限制 limit_req_module

# 连接限制
http {
//http段配置连接限制, 同⼀时刻只允许⼀个客户端IP连接
limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
 ...
 server {
 ... 
 location / {
 //同⼀时刻只允许⼀个客户端IP连接
 limit_conn conn_zone 1;
 }
//压⼒测试
yum install -y httpd-tools
ab -n 50 -c 20 http://www.wingsredevsecops.top/index.html

# 请求限制
http {
//http段配置连接限制, 同⼀时刻只允许⼀个客户端IP连接
limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
 ...
 server {
 ... 
 location / {
 //同⼀时刻只允许⼀个客户端IP连接
 limit_conn conn_zone 1;
 }
//压⼒测试
yum install -y httpd-tools
ab -n 50 -c 20 http://www.wingsredevsecops.top/index.html

访问控制

ip限制

//配置拒绝某⼀个IP, 其他全部允许
 location ~ ^/1.html {
 index index.html;
 deny 192.168.178.100;
 allow all;
}
//只允许某⼀个⽹段访问,其它全部拒绝
location / {
 index index.php index.html index.htm;
 allow 10.1.106.0/24;
 deny all;
}

用户登陆认证

[root@localhost:/etc/nginx/conf.d]# yum install http-tools -y
[root@localhost:/etc/nginx/conf.d]# rpm -ql httpd-tools
/usr/bin/ab # 压测工具
/usr/bin/htpasswd # 生成密码的工具

# 生成密码文件(-c创建新文件 -b允许命令行输入密码)
[root@localhost:/etc/nginx/conf.d]# htpasswd -b -c /etc/nginx/auth_pass mononoke 123456
Adding password for user mononoke
# 配置
[root@localhost:/etc/nginx/conf.d]# cat admin.conf 
server {
	listen 80;
	server_name admin.org;
	root /soft/code/;
	index index.html;
	
	location /admin/ {           
	# 用户名密码验证
        auth_basic "Auth access"; 
        auth_basic_user_file /etc/nginx/auth_pass; 
        # 来源IP限制
	allow 192.168.101.7;
	#deny all;                 
    }
}
image-20231118175037565

x_forwarded_for获取真实客户ip

# 在反向代理服务器添加x_forwarded_for获得真实ip
server {
    # 监听的IP和端⼝
    listen 80;
    # 域名
    server_name slb.wingsredevsecops.top;
    # 记录⽇志,使⽤⾃定义的log_format
    access_log /var/log/nginx/access.log main; 
    # 设置代理头部
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    # 正常的反向代理配置
    location / {
        # 后端Web服务器
        proxy_pass http://10.1.106.66;
    }
}

nginx静态服务

静态资源

image-20231118215856936

静态资源配置

sendfile # 文件读取高效
tcp_nopush # sendfile开启情况下, 提⾼⽹络包的`传输效率`
tcp_nodelay # 在keepalive连接下,提⾼⽹络的传输'实时性' 

gzip静态资源文件压缩

nginx将响应报文发送至客户端之前可以开启压缩功能,这能够有效的节约带宽,并提供响应至客户端的速度

Nginx 的 `gzip_comp_level` 配置项⽤于设置 Gzip 压缩的压缩级别,可选配置值为 1 到 9,数字越⼤表示压缩级别越⾼,压缩效果也更好,但相应地会消耗更多的 CPU 资源。
[root@localhost:/soft/code/images]# ll
总用量 928
-rw-r--r-- 1 root root 949042 8月  21 18:17 kagura.jpg
[root@localhost:/etc/nginx/conf.d]#  mkdir -p /soft/code/doc

[root@localhost:/etc/nginx/conf.d]# cat gzip.conf 
server {
	listen 80;
	server_name static.top;
	root /soft/code/images;
	index index.html index.htm ;
	sendfile on;
	access_log /var/log/nginx/static_access.log main;
	
	location ~ .*\.(jpg|gif|png)$ {
		gzip_http_version 1.1; # 压缩使用在http哪个协议, 主流版本1.1
		gzip_comp_level 9; # 压缩比例
		gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/xhttpd-php image/jpeg image/gif image/png;
		root /soft/code/images;
	}
	location ~ .*\.(txt|xml)$ { # 文件压缩
		gzip on;
		gzip_http_version 1.1;
		gzip_comp_level 1;
		gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/gif image/png;
		root /soft/code/doc;
		}
}

expires静态资源浏览器缓存

location ~ .*\.(js|css|html)$ {
 root /soft/code/images;
 expires 1h;
}
location ~ .*\.(jpg|gif|png)$ {
 root /soft/code/images;
 expires 7d;
}

页面会有过期时间

image-20231118231309869
//取消js css html等静态⽂件缓存
location ~ .*\.(css|js|swf|json|mp4|htm|html)$ {
add_header Cache-Control no-store;
add_header Pragma no-cache;
}

静态资源跨域访问

浏览器禁⽌跨域访问, 主要不安全, 容易出现 CSRF 攻击

# html文件
<html lang="en">
<head>
 <meta charset="UTF-8" />
 <title>测试ajax和跨域访问</title>
 <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
 $.ajax({
 type: "GET",
 url: "http://test.com",
 success: function(data) {
 alert("sucess!!!");
 },
 error: function() {
 alert("fail!!,请刷新再试!");
 }
 });
});
</script>
 <body>
 <h1>测试跨域访问</h1>
 </body>
</html>

[root@localhost:/etc/nginx/conf.d]# cat origin.conf 
server {
	listen 80;
	server_name origin.top;
	sendfile on;
	access_log /var/log/nginx/kuayu.log main;
	location ~ .*\.(html|htm)$ {
		root /soft/code/origin;
	}
}
[root@localhost:/etc/nginx/conf.d]# cat test.conf 
server {
	listen 80;
	server_name test.com;
	root /soft/code/test.com/;
	index index.html index.htm;
	add_header Access-Control-Allow-Origin *;
	add_header Access-Control-Allow-Credentials: true;
	add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
	add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,UserAgent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}

referers防盗链

server {
    listen 80;
    server_name refer.top ;
    root /soft/code/refer/;
    index index.html index.htm;
    //⽀持IP、域名、正则⽅式
    location ~ .*\.(jpg|gif|png)$ {
        valid_referers none blocked static.wingsredevsecops.top;
        if ($invalid_referer) {
            return 403;
        }
    	root /soft/code/images;
    }
}
posted @ 2023-11-18 23:48  mikrokosmo  阅读(43)  评论(0)    收藏  举报