Nginx优化 ab压力测试nginx--tomcat--httpd 防资源盗链 跨域访问 nginx优化总结

Nginx优化

什么是优化

了解知识

1、首先需要了解我们当前系统的结构和瓶颈,了解当前使用的是什么,运行的是什么业务,都有哪些服务,了解每个服务最大能支撑多少并发。比如nginx作为静态资源服务并发是多少,最高瓶颈在哪里,能支持多少qps(每秒查询率)的访问请求,那我们怎么得出这组系统结构瓶颈呢,比如top查看系统的CPU负载、内存使用率、总得运行进程等,也可以通过日志去分析请求的情况,当然也可以通过我们前面介绍到的stub_status模块查看当前的连接情况,也可以对线上的业务进行压力测试(低峰期),去了解当前这套系统能承担多少的请求和并发,以做好响应的评估。这个是我们做性能优化最先考虑的地方。  ## 服务的极限 最高支持50000并发

2、其次我们需要了解业务模式,虽然我们是做性能优化,但每一个性能的优化都是为业务所提供的服务的,我们需要了解每个业务接口的类型,比如:电商网站中的抢购模式,这种情况下,平时没什么流量,但到了抢购时间流量会突增。我们还需要了解系统层次化的结构,比如:我们使用nginx做的是代理、还是动静分离、还是后端直接服务用户,那么这个就需要我们对每一层做好相应的梳理。以便更好的服务业务。

3、最后我们需要考虑性能与安全,往往注重了性能,但是忽略了安全。往往过于注重安全,对性能又会产生影响。比如:我们在设计防火墙功能时,检测过于严密,这样就会给性能带来影响。那么如果对于性能完全追求,却不顾服务的安全,这个也会造成很大的隐患,所以需要评估好两者的关系,把握好两者的孰重孰轻。以及整体的相关性,权衡好对应的点。
1.首先需要了解我们当前系统的结构和瓶颈
# 结构和瓶颈 : 了解我们的服务器的各个配置,例如负载均衡,如果至于七层,表示我们端口至于65535个,假如用户访问量多,可能会不够,那是否需要做4层负载均衡添加端口。
# 了解七层负载均衡下面的web服务器的硬件性能都是怎样的,内存,硬件,CPU。目前现在的web服务器够支持服务吗?
# mysql有多少台.假如客户的访问量大,导致WEB端访问mysql的量也大,那么mysql是否做了主从,以及读写分离,分担数据库的压力。
# 静态共享文件用的是什么?是NFS还是分布式文件系统?、、

2、其次我们需要了解业务模式,
# 例如双十一电商网站中的抢购模式,这种情况下,平时没什么流量,但到了抢购时间流量会突增。我们还需要了解系统层次化的结构,登录,用户管理,购物车,支付,浏览,双十一的时候,会对,购物车,支付以及浏览的要求量比较大,这时候,我们是否应该针对购物车,支付,以及浏览的web端多添加一台机器,缓解压力。
`重点来说,看自己的业务模式,针对压力大的服务,来进行优化,或者添加硬件配置。

3.我们还需要了解系统层次化的结构

4.最后我们需要考虑性能与安全

# 对于性能以及安全,查看公司的业务系统,是关于金融,游戏。电商等,各个不同,对于安全性以及性能的取舍也不同。

Nginx从哪些方面入手进行优化

# OSI七层模型:物理层,数据链路层,网络层,传输层,会话层,表示层,应用层

# 1.物理层,硬件:
		1、nginx做负载均衡只需要cpu核心多一些
		2、静态资源存储,磁盘大一些
		3、nginx做动态资源代理,CPU
		4、ES,redis服务内存需要大一些
		
# 2.网络层:
		1、丢包、延迟
		2、带宽
		
# 3.系统:对linux系统优化
		1、打开文件数 --- #文件描述符
	 	2、端口复用 --- # 强制使用time_wait端口
	 	'即服务器之间的连接,例如web01的'7890'端口连接数据库的'80'端口,他们之间的连接也是tcp3次握手协议。针对TCP4次挥手。因为在服务端结束后,也就是第三次挥手的时候会有个'time_wait'等待释放时间,这个时间段大概是1-4分钟,在这1-4分钟内不能使用,在这个时间内,端口不会迅速的被释放,所以可通过端口复用的方法来解决这个问题'
	 	
# 4.应用:tcp长连接 -- (比较块,一次链接,多次请求)
		不仅仅是用户访问服务器的,'负载均衡的keepalived',负载均衡连接web,web连接php,数据库,共享文件等,都是短链接,需要我们优化为长链接。

# 5.服务:服务的针对性优化

影响性能的指标

1.网络   # 丢包,延迟
2.系统   # 文件描述符,端口的复用,系统的内存/负载
3.服务   # 
4.程序   # 开发代码(不关我们事)
5.数据库 # 读写分离,主从,高可用,索引等。

ab压力测试工具

安装ab测试工具

为什么用nginx做web服务?nginx性能最优,在处理静态文件速度比apache,tomcat快。
用ab测试工具,测试tomcat以及nginx之间,那个处理的速度比较快。

#查看命令所在的包
[root@web01 ~]# yum provides ab

#安装ab
[root@web01 ~]# yum install -y httpd-tools

工具使用

[root@web01 ~]# ab -n 200 -c 2 http://www.baidu.com/  ##必须加根/

-n	请求的次数
-c	请求的并发数
-k	开启长连接

Usage: ab [options] [http[s]://]hostname[:port]/path

配置nginx网站

[root@web01 conf.d]# vim linux.ab.conf 
server {
    listen 80;
    server_name linux.ab.com;
    root /code;

    location / {
        try_files $uri $uri/ @java;
    }

    location @java {
        proxy_pass http://172.16.1.8:8080;
    }
}

[root@web01 conf.d]# echo "test nginx web" > /code/index.html

[root@web01 conf.d]# echo "test try_file" > /code/index.html

# 授权: chown -R www.www /code/
## 检查nginx -t 并重启

[root@web01 conf.d]# systemctl restart nginx

本地hosts访问  192.168.15.7 linux.ab.com

配置hosts压测nginx访问静态资源

nginx 测试的比较快

[root@web01 conf.d]# vim /etc/hosts

192.168.15.7 linux.ab.com

[root@web01 conf.d]# ab -n 50000 -c 200 http://linux.ab.com/

Concurrency Level:      200
Time taken for tests:   10.534 seconds
Complete requests:      50000
Failed requests:        0
Write errors:           0
Total transferred:      13600000 bytes
HTML transferred:       1000000 bytes
Requests per second:    4746.50 [#/sec] (mean)
Time per request:       42.136 [ms] (mean)
Time per request:       0.211 [ms] (mean, across all concurrent requests)
Transfer rate:          1260.79 [Kbytes/sec] received

压测tomcat访问静态资源

[root@web01 conf.d]# mv /code/ /node

[root@web01 conf.d]# ab -n 50000 -c 200 http://linux.ab.com/
Server Software:        nginx/1.18.0
Server Hostname:        linux12.ab.com
Server Port:            80

Document Path:          /
Document Length:        20 bytes

Concurrency Level:      200
Time taken for tests:   9.664 seconds
Complete requests:      50000
Failed requests:        0
Write errors:           0
Total transferred:      13600000 bytes
HTML transferred:       1000000 bytes
Requests per second:    5173.97 [#/sec] (mean)
Time per request:       38.655 [ms] (mean)
Time per request:       0.193 [ms] (mean, across all concurrent requests)
Transfer rate:          1374.34 [Kbytes/sec] received

压测httpd访问静态资源

[root@web01 conf.d]# yum install -y httpd
[root@web01 conf.d]# echo "test httpd" > /var/www/html/index.html
[root@web01 conf.d]# systemctl stop nginx
[root@web01 conf.d]# systemctl start httpd

[root@web01 conf.d]# ab -n 50000 -c 200 http://192.168.15.7/
Server Software:        Apache/2.4.6
Server Hostname:        10.10.0.7
Server Port:            80

Document Path:          /
Document Length:        11 bytes

Concurrency Level:      200
Time taken for tests:   8.925 seconds
Complete requests:      50000
Failed requests:        0
Write errors:           0
Total transferred:      14050000 bytes
HTML transferred:       550000 bytes
Requests per second:    5602.52 [#/sec] (mean)
Time per request:       35.698 [ms] (mean)
Time per request:       0.178 [ms] (mean, across all concurrent requests)
Transfer rate:          1537.41 [Kbytes/sec] received

结论

nginx处理静态资源的速度比其他web服务要快

tomcat安装

下载或上传tomcat包

# 网站下载 http://tomcat.apache.org/  -------》download------》tomcat 9----》复制连接tar.gz --------》下载解压

[root@web01 ~]# mkdir /service
[root@web01 ~]# cd /service
[root@web01 service]# ll
total 5884
-rw-r--r-- 1 root root 6022059 Apr 10 16:29 apache-tomcat-9.0.41-src.tar.gz

解压代码包

# 1.上传并解压至指定文件夹
[root@web01 service]# tar xf jdk-8u40-linux-x64.gz -C /service/
[root@web01 service]#yum install java-1.8.0-openjdk -y
#出现以下界面java依赖安装成功
[root@lb02 apache-tomcat-9.0.45]# java -version
openjdk version "1.8.0_292"
OpenJDK Runtime Environment (build 1.8.0_292-b10)
OpenJDK 64-Bit Server VM (build 25.292-b10, mixed mode)
[root@web01 service]# mv jdk1.8.0_40 java1.8


# 2.修改添加环境变量
[root@web01 service]# vim /etc/profile.d/java.sh
export JAVA_HOME=/service/java1.8
export JRE_HOME=/service/java1.8/jre
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib:$JRE_HOME/lib:$CLASSPATH
export PATH=$PATH:$JAVA_HOME/bin
[root@web01 service]# source /etc/profile


#修改端口(视情况而定)
[root@web01 service]# sed -i 's#8080#80#g' /usr/local/apache-tomcat-9.0.45/conf/server.xml

配置tomcat页面

[root@web01 service]# echo "linux12_tomcat" > apache-tomcat-8.5.51/webapps/ROOT/index.html

启动tomcat并查看日志

[root@web01 service]# /service/apache-tomcat-8.5.51/bin/startup.sh && tail -f /service/apache-tomcat-8.5.51/logs/catalina.out

文件句柄优化

可打开的最大文件数量

# 1、查看文件句柄数设置

[root@lb01 ~]# ulimit -n
1024

# 2.查看打开的文件句柄数 (安装lsof软件)

[root@lb01 ~]# lsof | wc -l
3061
[root@web01 ~]# lsof | wc -l
5060

# 3.查看指定服务的打开文件句柄数

[root@web01 ~]# lsof -p 31491  | wc -l   #31491  :查看同一个服务打开的所有文件数是多少。

# 4.设置文件句柄数 -- 系统全局的设置

[root@web01 ~]# vim /etc/security/limits.conf
* - nofile 65535
* soft nofile 65535
* hard nofile 65535 
*		#所有用户
-		#当超过设置的文件句柄数时,什么都不干
soft	#当超过设置的文件句柄数时,仅提示
hard	#当超过设置的文件句柄数时,直接限制


# 5.设置文件句柄数 -- 用户局部局的设置

[root@web01 ~]# vim /etc/security/limits.conf
root - nofile 65535
root soft nofile 65535
root hard nofile 65535

# 6.针对某一个服务设置 文件巨柄

'以NGINX为例子,修改它的文件句柄,其他的服务通路,找到某项服务的主配置文件,
[root@lb01 ~]# vim /etc/nginx/nginx.conf 
user  www;
worker_processes  1;
worker_rlimit_nofile 65535; # 修改nignx的最大文件句柄为65535.

系统层面优化 (内核优化)

[root@lb01 ~]# vim /etc/sysctl.conf
net.ipv4.tcp_fin_timeout = 2
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_tw_reuse = 1  #tw 就是time wait  开启time wait 使用
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.ip_local_port_range = 4000 65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_orphans = 16384
net.ipv4.ip_forward = 1    #开启IP转发,默认是开启的

[root@lb01 conf.d]# sysctl -p   #生效
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_tw_reuse = 1 

代理服务优化

# tcp长连接 -- (比较块,一次链接,多次请求)
# 不仅仅是用户访问服务器的,'负载均衡的keepalived',负载均衡连接web,web连接php,数据库,共享文件等,都是短链接,需要我们用到代理,优化为长链接。

配置用户访问负载均衡的长连接

[root@lb01 ~]# vim /etc/nginx/nginx.conf
... ...
http {
	... ...
	keepalive_timeout  65;
	... ...
}

配置负载均衡反向代理到web的长连接

[root@lb01 ~]# vim /etc/nginx/conf.d/linux.keep.conf
upstream tomcat {
    server 172.16.1.7:8080;
    keepalive 8;  #配置开启长连接,16,32也是同样开启长连接
}

server {
    listen 80;
    server_name linux.keep.com;

    location / {
        proxy_pass http://tomcat;
        proxy_http_version 1.1; #代理带后端的http版本,1.0是短链接,1.1是长链接。
        proxy_set_header Connection "";	 #清除请求头字段
        include proxy_params;
    }
}

# 代理nginx也可以  把8080改成80就行

配置web代理到php保持长连接

[root@web01 ~]# vim /etc/nginx/conf.d/linux.wp.conf 
## 这是基于负载均衡,使用我代理我自己方式,开启长链接。
upstream php_server {
    server 127.0.0.1:9000;
}

server {
    listen 80;
    server_name linux.wp.com;

    location / {
        root /code/wordpress;
        index index.php;
    }

    location ~* \.php$ {
        fastcgi_pass php_server;
        fastcgi_param SCRIPT_FILENAME /code/wordpress/$fastcgi_script_name;
        fastcgi_param HTTPS on;
        fastcgi_keep_conn on;  # 表示对于'php_server'开启长链接
        include fastcgi_params; 
    }
}

代理优化配置

[root@lb01 ~]# vim /etc/nginx/proxy_params 
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;
proxy_connect_timeout 20s;
proxy_read_timeout 20s;
proxy_send_timeout 20s;
proxy_buffering on;
proxy_buffer_size 8k;
proxy_buffers 8 8k;
proxy_next_upstream http_500 http_502 http_503 http_504;

静态资源优化

静态资源缓存

# 类型	         后缀

图片文件	gif、png、jpg、jpeg
视频文件	mp4、avi、rmvb
其他文件	txt、xml、pdf
样式文件	css、js、html

在这里插入图片描述

### 此bash都是在浏览器的内容

#响应头部
cache-control: max-age=15552000
expires: Fri, 01 Jan 2905 00:00:00 GMT
last-modified: Mon, 28 Sep 2970 06:00:00 GMT
ETag: "5fd6c1d9-7cda"

#请求头部
If-None-Match: "5fs2c4d9-7cda"
If-Modified-Since: Sat, 13 Sep 2021 15:43:09 GMT

浏览器缓存

# 1、浏览器缓存原理

1.浏览器先去查看响应头部的 cache-control
2.如果没有超过缓存时间,直接返回浏览器缓存的内容
3.如果 cache-control 设置为 no-cache,浏览器会继续去读取 expires
4.如果没有到达 expires 设置的时间,那么浏览器会读取缓存
5.如果 cache-control 和 expires 都没有设置
6.浏览器会去查看服务器上面的 ETag
7.服务器上如果有 ETag,那么浏览器会拿着 If-None-Match 与其对比,如果值相同,那么走缓存
8.如果 ETag 与 If-None-Match 不同,浏览器会读取服务器上的 last-modified
9.服务器上如果有 last-modified,那么浏览器会拿着 If-Modified-Since 与其对比,如果值相同,那么走缓存
10.如果 last-modified 与 If-Modified-Since 不同,则不走缓存,需要重新到服务器上获取数据并返回


# 2、浏览器缓存参数含义

1.cache-control:'缓存控制,记录的是文件的保留时长
2.expires:'缓存到期时间
3.ETag:'服务器上保留的文件的唯一识别符
4.If-None-Match:'浏览器上上保留的文件的唯一识别符
5.last-modified:'服务器上保留的文件的最后修改时间
6.If-Modified-Since:'浏览器上保留的文件的最后修改时间

静态资源优化

1.静态资源
2.静态资源缓存
1.Etag:服务器上的文件唯一标示
2.Last-Modified:服务器上的文件最后修改时间
3.Expires:文件缓存过期时间
4.Cache-Control:文件多久过期
5.If-None-Match:浏览器上的文件唯一标示
6.If-Modified-Since:浏览器上的文件最后修改时间

配置缓存过期时间

#  模块 ngx_http_headers_module.html (默认开启的)
#语法                                   
Syntax:	expires [modified] time;
		expires epoch | max | off;
Default:	expires off;
Context:	http, server, location, if in location

#配置
[root@web01 conf.d]# vim linux.cache.conf
server {
    listen 80;
    server_name linux.cache.com;

    location ~* \.(png|jpg|gif)$ {
        root /code/cache;
        expires 10d;  # 此配置默认关闭了nginx 的 Expires 以及 Cache-Control
        #这里打开是设置了 Expires 文件缓存10天,以及 Cache-Control 10天过期
        # 默认10天之后缓存失效
    }
}
[root@web01 ~]# mkdir /code/cache
[root@web01 ~]# cd /code/cache
[root@web01 cache]# rz                        
[root@web01 cache]# ll
-rw-r--r--  1 www www 140135 Mar 27 18:32 8.png

## 授权
[root@web01 ~]# chown -R www.www /mm/index.html

## nginx -t检查并重启
[root@web01 ~]# systemctl restart nginx

# 配置本地hosts
192.168.15.7  linux.cache.com

设置不走缓存

1.使用无痕模式

2.开启浏览器上面的 Disable cache  # 右键点击检查/ Disable cache #选择这个

3.配置nginx关闭缓存

[root@web01 conf.d]# vim linux.cache.conf
server {
    listen 80;
    server_name linux.cache.com;

    location ~* \.(png|jpg|gif)$ {
        root /code/cache;
        etag off; #关闭服务器上的文件唯一标示,浏览器于服务器的 etag 对不上,就不会走这个缓存。
        add_header Cache-Control no-cache; #请求头以及缓存关闭
        if_modified_since off; #不开启浏览器上的 If-Modified-Since 文件最后修改时间,所以和服务器的 If-Modified 对不上
    }
}

静态资源读取优化

#1. 文件高效读取

#高效传输,上nginx访问数据,就只需要在用户空间(应用程序)内进行,不需要通过内核空间传回给用户空间(CPU,硬件等).
'配置在'`/etc/nginx/nginx.conf`'的主配置文件里'
'在http层配置,默认为关闭,'`sendfile on;`'为开启 '
Syntax:	sendfile on | off;
Default:	sendfile off;
Context:	http, server, location, if in location

# 2.文件高效传输

#将多个数据打个包,一次推送,大文件适合此配置,需要开启 sendfile
'配置在'`/etc/nginx/nginx.conf`'的主配置文件里'
'在http层配置,默认为关闭状态,'`tcp_nopush on;`'不过传输会变慢。。。'
Syntax:	tcp_nopush on | off;
Default:	tcp_nopush off;
Context:	http, server, location

# 3.长连接

#开启长链接,这里的长链接是客户通过浏览器,访问服务器的网页。一次请求,可以有多次连接,在规定的时间内,可以不用建立TCP链接。
'配置在'`/etc/nginx/nginx.conf`'的主配置文件里'
'在http层配置,默认为开启状态'
Syntax:	keepalive_timeout timeout [header_timeout];
Default:	keepalive_timeout 75s;
Context:	http, server, location

# 4.长连接传输

#来一条数据传输一条数据,需要开启 keepalive
'配置在'`/etc/nginx/nginx.conf`'的主配置文件里'
'在http层配置,默认为关闭状态,需要开启'`keepalive`',一般配这个'
Syntax:	tcp_nodelay on | off;
Default:	tcp_nodelay on;
Context:	http, server, location

# 5.静态资源压缩

'静态资源压缩配置语法
#开启压缩
'配置在'`/etc/nginx/nginx.conf`'的主配置文件里'
'默认为关闭状态, '`gzip on;`'为开启静态资源压缩,需要和他嵌套的语法配合才有用。
Syntax:	gzip on | off;
Default:	gzip off;
Context:	http, server, location, if in location

#指定压缩静态文件的类型,可指定多个

'最好配置在'`/etc/nginx/nginx.conf`'的主配置文件里。与'`gzip on; gzip_http_version 1.1;`'配合。
'表示需要进行压缩的文件类型。'`gzip_types image/jpeg image/gif image/png;`',表示对此服务的,jpg,gif,png,进行压缩。'
Syntax: gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript  image/gif image/jpeg image/png;
gzip_comp_level 5;;
Default:	gzip_types text/html;
Context:	http, server, location

#指定压缩的级别,压缩比例(压缩的等级越大,消耗的CPU越多,压缩的比例越大)

'最好配置在'`/etc/nginx/nginx.conf`'的主配置文件里。
''`gzip_comp_level 5;`',开启的压缩的等级为5
Syntax:	gzip_comp_level level;
Default:	gzip_comp_level 1;   #共1-9个级别,一般我们设置3-5
Context:	http, server, location

#压缩后传输使用的协议

'最好配置在'`/etc/nginx/nginx.conf`'的主配置文件里。
'gzip_http_version 1.1;'
Syntax:	gzip_http_version 1.0 | 1.1; 
Default:	
Context:	http, server, location

## 珍贵的例子 --- r压缩配置

[root@web01 cache]# vim /etc/nginx/conf.d/linux.gzip.conf 
server {
    listen 80;
    server_name linux.gzip.com;

    location ~* \.(png|jpg|gif)$ {
        root /code/cache;
        gzip on;   #开启压缩
        gzip_types image/jpeg image/gif image/png;  #指定压缩文件的类型
        gzip_comp_level 4;   #指定压缩的级别,压缩比例
        gzip_http_version 1.1;	#压缩后传输使用的协议
    }

    location ~* \.txt$ {
        root /code/cache;
        gzip on;
        gzip_types text/plain;
        gzip_comp_level 5;
        gzip_http_version 1.1;
    }
}

## 授权
[root@web01 ~]# chown -R www.www /code/

## nginx -t检查并重启
[root@web01 ~]# systemctl restart nginx

# 配置本地hosts
192.168.15.7  linux.gzip.com

防资源盗链

配置被盗连的网站

[root@web01 code]# cat /etc/nginx/conf.d/linux.beidaolian.conf 
server {
listen 80;
    server_name linux.daolian.com;

    # location ~* / {   #两者都可以
     location  / {
        root /code;
        index index.html;
    }
}

#准备站点和文件
[root@web01 code]# vim index.html 
2021加油,被盗

## 授权
[root@web01 ~]# chown -R www.www /code/

## nginx -t检查并重启
[root@web01 ~]# systemctl restart nginx

# 配置本地hosts

192.168.15.7  linux.beidaolian.com

[root@web01 code]# ll
total 996
-rw-r--r--  1 www www 857244 Apr 11 19:36 404.png
-rw-r--r--  1 www www 140135 Mar 27 18:32 8.png

 http://linux.beidaolian.com/404.png   #这样的话可以看到404.png的图片了

配置盗链的网站

[root@lb01 conf.d]# vim linux.daolian.conf
server {
    listen 80;
    server_name linux.daolian.com;

    location / {
        root /code;
	index index.html;
    }
}


#准备站点
[root@lb01 code]# vim index.html 
<html>
<body>
<img src="http://linux.beidaolian.com/404.png"
</body>
</html>  

## 授权
[root@web01 ~]# chown -R www.www /code/

## nginx -t检查并重启
[root@web01 ~]# systemctl restart nginx

# 配置本地hosts
192.168.15.5  linux.daolian.com

配置hosts访问测试

192.168.15.5  linux.daolian.com
192.168.15.7  linux.beidaolian.com

#windows访问
http://linux.daolian.com/

在这里插入图片描述

配置防盗链

ngx_http_referer_module   #模块

# 防盗链语法,   
# 说白了就是判定,用户的请求,是否从自己的域名定位到这里。
Syntax:	valid_referers none | blocked | server_names | string ...;
Default:	—
Context:	server, location

none			#nginx日志中referer部分为空
blocked 		#nginx日志中referer部分没有协议
server_names	#nginx日志中referer部分为指定的域名
string			#nginx日志中referer部分为指定的域名(可以使用正则表达式)

## 配置域名查看 用curl linux.daolian.com
[root@web01 nginx]# cat /etc/hosts

192.168.15.5  linux.daolian.com
192.168.15.7  linux.beidaolian.com

`# 案列
[root@web01 conf.d]# vim linux.beidaolian.conf 
server {
    listen 80;
    server_namelinux.beidaolian.com;

    location / {
        root /code;
        index index.html;
    }

    location ~* \.jpg$ {
        root /code;
        valid_referers none blocked server_names;  #开启防盗链模块,判断域名不上来着自己网站则重定向到500.后端错误。
        if ($invalid_referer) {   
           return 500;
        }
    }
}

伪造请求头

#模拟请求头为 http://linux.daolian.com 访问图片

[root@lb01 ~]# curl -e "http://linux.daolian.com" -I http://linux.beidaolian.com/404.png
HTTP/1.1 500 Internal Server Error
Server: nginx/1.18.0
Date: Tue, 15 Dec 2020 02:51:41 GMT
Content-Type: text/html; charset=utf8
Content-Length: 177
Connection: close


#模拟请求头为 http://linux.beidaolian.com 访问图片

[root@lb01 nginx]# curl -I http://linux.beidaolian.com/404.png
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Sun, 11 Apr 2021 14:22:41 GMT
Content-Type: image/png
Content-Length: 857244
Last-Modified: Sun, 11 Apr 2021 12:15:06 GMT
Connection: keep-alive
ETag: "6072e84a-d149c"
Accept-Ranges: bytes

允许多个域名盗链

[root@web01 conf.d]# vim linux.beidaolian.com.conf 
server {
    listen 80;
    server_name linux.beidaolian.com;

    location / {
        root /code;
        index index.html;
    }

    location ~* \.jpg$ {
        root /code;
        valid_referers none blocked server_names *.baidu.com;
        if ($invalid_referer) {
           return 500;
        }
    }
}

[root@lb01 ~]# curl -e "http://www.baidu.com" -I http://linux.beidaolian.com/404.png
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Sun, 11 Apr 2021 14:22:41 GMT
Content-Type: image/png
Content-Length: 857244
Last-Modified: Sun, 11 Apr 2021 12:15:06 GMT
Connection: keep-alive
ETag: "6072e84a-d149c"
Accept-Ranges: bytes

盗链和跨域的区别

盗链是由盗链的网站向被盗链的网站发起get请求获取内容

跨域是由跨域的网站向被跨域的网站发起一个完整http请求,甚至是完全跳转

什么是跨域访问

当我们通过浏览器访问a⽹站时,同事会利⽤到ajax或其他⽅式,同时也请求b⽹站,这样的话就
出现了请求⼀个⻚⾯,使⽤了两个域名,这种⽅式对浏览器来说默认是禁⽌的。

配置被跨域的网站

[root@web01 conf.d]# vim linux.beikuayu.conf
server {
    listen 80;
    server_name linux.beikuayu.com;

    location / {
        root /code;
        index index.html;
    }   
}

#配置站点
[root@web01 code]# cat index.html 

2021被跨越网站!

## 授权
[root@web01 ~]# chown -R www.www /code/

## nginx -t检查并重启
[root@web01 ~]# systemctl restart nginx

# 配置本地hosts
192.168.15.7  linux.beikuayu.com

配置跨域网站

[root@lb01 conf.d]# vim linux.kuayu.conf 
server {
    listen 80;
    server_name linux.kuayu.com;

    location ~* / {
        root /code;
        index index.html;
    }
}

#配置跨域的站点文件
[root@lb01 conf.d]# vim /code/index.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://linux.beikuayu.com",
        success: function(data) {
                alert("sucess 哎哟 不错 成功了!!!");
        },
        error: function() {
                alert("fail!!,我靠,TM的不让进去啊,只能蹭蹭");
        }
        });
});
</script>
        <body>
                <h1>测试跨域访问啊</h1>
        </body>
</html>

#配置站点
[root@ lb01 code]# cat index.html 

2021被跨越网站!

## 授权
[root@ lb01 ~]# chown -R www.www /code/

## nginx -t检查并重启
[root@ lb01 ~]# systemctl restart nginx

# 配置本地hosts
192.168.15.5  linux.kuayu.com

配置本地hosts测试

#windows的hosts

192.168.15.5  linux.kuayu.com
192.168.15.7  linux.beikuayu.com

[root@web01 conf.d]# vim /etc/hosts
192.168.15.5  linux.kuayu.com
192.168.15.7  linux.beikuayu.com

[root@lb01 conf.d]# vim /etc/hosts
192.168.15.5  linux.kuayu.com
192.168.15.7  linux.beikuayu.com

# 5.测试跨域访问

http://linux.kuayu.com/

http://linux.beikuayu.com/

配置允许被跨域

[root@web01 conf.d]# vim linux.beikuayu.conf 
server {
    listen 80;
    server_name linux.beikuayu.com;

    location / {
        root /code;
        index index.html;
        #允许跨域的网站
        add_header Access-Control-Allow-Origin *;
        #允许跨域网站发起的请求类型
        add_header Access-Control-Allow-Methods 'GET,POST,PUT,DELETE,OPTIONS';
    }
}

nginx的CPU亲和

CPU亲和(affinity)减少进程之间不断频繁切换,减少性能损耗,其实现原理是建CPU核⼼和Nginx⼯作进程绑
定⽅式,把每个worker进程固定到对应的cpu上执⾏,减少切换CPU的cache miss,获得更好的性能。

查看cpu状态

## 首先要根据的电脑配置查看自己多少CPU!

[root@web01 ~]# lscpu
CPU(s):                2    #cpu数
On-line CPU(s) list:   0-1  #cpu核心数
Thread(s) per core:    1    #1块cpu
Core(s) per socket:    1
NUMA node0 CPU(s):     0-1

修改nginx配置

[root@web01 ~]# vim /etc/nginx/nginx.conf 
worker_processes  2;

[root@web01 ~]# systemctl restart nginx

没有配置亲和的情况

[root@web01 conf.d]# ps -eo pid,args,psr | grep [n]ginx
  1869 nginx: master process /usr/   1
  1870 nginx: worker process         1  #两个cpu都在抢占1的cpu,默认从0开始。

配置cpu亲和

# 1.方式1
worker_processes    2;
worker_cpu_affinity 0001 0010 ;

worker_processes    8;
worker_cpu_affinity 00000001 00000010 ...;

# 2.方式2
worker_processes    2;
worker_cpu_affinity 0101 1010;
  
# 3.方式3
'表示'`nginx`'里的每个'`worker`'自动平均分配CPU。
worker_processes auto;
worker_cpu_affinity auto;

[root@web01 ~]# vim/etc/nginx/nginx.conf
---------------------------- `核心模块` ---------------------------
user  www; #启动此进程的用户   # 增加下面两行
worker_processes  auto;   	# master给worker分配工作,worker的数量,与CPU的数量相关
worker_cpu_affinity auto; 	# 自动平均分配CPU。

配置CPU亲和后

[root@web01 conf.d]# ps -eo pid,args,psr | grep [n]ginx
  2070 nginx: master process /usr/   1
  2071 nginx: worker process         0
  2072 nginx: worker process         1

nginx通用优化文件

通用优化配置

[root@web01 conf.d]# cat /etc/nginx/nginx.conf

user www;									#nginx启动用户
worker_processes auto;						 #nginx工作进程数
worker_cpu_affinity auto;					  #开启CPU亲和
error_log /var/log/nginx/error.log warn;	  #错误日志,存放路径,记录日志的级别
pid /run/nginx.pid;							#指定pid文件位置
worker_rlimit_nofile 1024;					 #指定nginx服务的最大打开文件数

events {
    use epoll;								 #使用epoll网络模型
    worker_connections 10240;				 #worker工作进程的最大连接数
}

http {
    include             mime.types;				    #nginx能识别的文件类型
    default_type        application/octet-stream;   #nginx不识别的文件类型默认下载

   log_format  main  '$remote_addr - $remote_user [$time_local] "$request" 
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';	 #配置日志格式
                      
                      
log_format json_access '{"@timestamp":"$time_iso8601",'
                     '"host":"$server_addr",'
                     '"clientip":"$remote_addr",'
                     '"size":$body_bytes_sent,'
                     '"responsetime":$request_time,'
                     '"upstreamtime":"$upstream_response_time",'
                     '"upstreamhost":"$upstream_addr",'
                     '"http_host":"$host",'
                     '"url":"$uri",'
                     '"domain":"$host",'
                     '"xff":"$http_x_forwarded_for",'
                     '"referer":"$http_referer",'
                     '"status":"$status"}';                    #定义json格式⽇志   
                                           
    charset utf-8;								    #指定字符
    access_log  /var/log/nginx/access.log  main		#指定访问日志路径,调用日志的格式
    server_tokens off;							    #隐藏版本号
    client_max_body_size 500m;					    #上传文件大小限制
    sendfile            on;						    #高效读取
    tcp_nopush          on;							#高效传输
    #tcp_nodelay         on;						#实时传输
    keepalive_timeout   65;							#开启长连接
    gzip on;									    #开启压缩
    gzip_disable "MSIE [1-6]\.";					#指定不压缩的浏览器
    gzip_http_version 1.1;							#压缩后传输的协议
    gzip_comp_level 5;								#压缩的级别
    gzip_buffers 16 10k;								#压缩缓存
    gzip_min_length 1024;							#开启压缩的最小值
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript image/jpeg;		#压缩的文件类型
    include /etc/nginx/conf.d/*.conf;				#包含的配置文件
}

nginx优化总结

1、CPU亲和、worker进程数、调整nginx进程打开的文件句柄数
2、使用Epool网络模型、调整每个worker进程的最大连接数
3、文件的高效读取sendfile、nopush
4、文件的传输实时性、nodealy
5、开启tcp长连接,以及长连接超时时间keepalive_timeout
6、开启文件传输压缩gzip
7、开启静态文件expires缓存
8、隐藏nginx版本号
9、禁止通过ip地址访问,禁止恶意域名解析,只允许域名访问
10、配置防盗链、以及跨域访问
11、防DDOS、cc攻击,限制单IP并发连接,以及http请求
12、优雅显示nginx错误页面
13、nginx加密传输https优化
14、nginx proxy_cache、fastcgi_cache、uwsgi_cache 代理缓存,第三方工具(squid、varnish)
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

琴声浮或沉__听懂只一人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值