当前位置: 首页 > news >正文

nginx常用配置及调优

文章目录

    • nginx编译安装
    • php编译安装
      • 整合nginx连接php
      • 测试LNMP环境的PHP服务是否可以连接mysql
    • nginx配置ssl证书及http跳转https
    • 编译安装nginx后新添加模块
    • 隐藏nginx版本号和标识
    • 配置nginx运行用户和cpu亲和性
    • 优化nginx事件处理模型
    • 优化nginx最多可打开文件数
    • 优化nginx进程最大并发连接数
    • 虚拟主机(servername)和location匹配规则
    • FastCGI缓存调优
    • 开启高效传输模式
    • 开启gzip压缩
    • expires浏览器缓存调优
    • 禁止使用ip地址访问网站
    • 设置301永久跳转
    • 防盗链设置
    • 限制连接数
    • nginx日志切割

nginx编译安装

本文章使用nginx1.24版本

安装编译依赖

yum install -y gcc gcc-c++ zlib zlib-devel libffi libffi-devel openssl openssl-devel pcre pcre-devel yum-utils wget tree autoconf automake

创建用户

useradd -s /sbin/nologin -M nginx

编译安装

tar -xf nginx-1.24.0.tar.gz -C /usr/local/src
cd /usr/local/src/nginx-1.24.0./configure --prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module \
--with-http_sub_module \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-http_realip_module \
--with-http_dav_module \
--with-http_addition_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-pcre \
--with-stream #检查配置参数过程中是否出错
echo $?
0
make && make install

修改nginx配置文件,将用户改为nginx

vim /usr/local/nginx/conf/nginx.confuser  nginx;

添加环境变量

vi /etc/profile
#最后加入
nginx_sbin="/usr/local/nginx/sbin/"
export PATH=$PATH:$nginx_sbinsource /etc/profile

也可创建链接文件

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

编写systemd单元文件管理nginx服务

通常在/usr/lib/systemd/system/或/etc/systemd/system/目录下创建nginx.service文本文件

vi /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx high performance web server
After=network.target remote-fs.target nss-lookup.target[Service]
Type=forking
#PIDFile=/var/run/nginx/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true[Install]
WantedBy=multi-user.target

重载配置

systemctl daemon-reload

启动并加入开机自启动

systemctl enable nginx --now

php编译安装

安装所需依赖包

yum install -y epel-release
yum --enablerepo=devel -y install oniguruma-devel
yum install -y libxml2 libxml2-devel openssl-devel bzip2-devel libjpeg libjpeg-devel libpng-devel libpng curl libcurl-devel libxslt-devel libzip sqlite-devel libmcrypt-devel libmcrypt php-pear libtool autoconf libcurl-devel xz-devel freetype-devel libicu-devel

oniguruma安装源

cat <<EOF > /etc/yum.repos.d/devel.repo
[develrepo]
name= devel repo
baseurl=https://mirror.sjtu.edu.cn/rocky/8/devel/x86_64/os/
enabled=1
gpgcheck=0
EOF

创建www用户

useradd www-data -M -s /sbin/nologin

编译安装

#进入解压目录
tar -xf php-7.4.33.tar.gz -C /usr/local/src/
cd /usr/local/src/php-7.4.33#配置编译选项
./configure --prefix=/usr/local/php --with-mysqli=mysqlnd --with-mhash --with-iconv --with-openssl --with-zlib --with-xmlrpc --without-pear --with-gettext --with-libxml --with-bz2 --with-jpeg --enable-gd --with-curl --enable-inline-optimization --enable-soap --enable-mbstring --disable-mbregex --enable-xml --enable-fpm --with-fpm-user=www-data --with-fpm-group=www-data#编译并安装
make -j 4 && make install# 从解压源码包中拷贝配置文件
cp /usr/local/src/php-7.4.33/php.ini-production /usr/local/php/php.ini
cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.conf
cp /usr/local/src/php-7.4.33/sapi/fpm/php-fpm.service /usr/lib/systemd/system/php-fpm.service#修改
vim /usr/lib/systemd/system/php-fpm.service
20 # Mounts the /usr, /boot, and /etc directories read-only for processes invoked by thi    s unit.
21 ProtectSystem=false  #将原来的true改为false

重载配置

systemctl daemon-reload

启动并加入开机自启动

systemctl enable php-fpm --now

整合nginx连接php

在nginx配置中加入以下配置

# http块中写入locationlocation ~ \.php$ {root           html;fastcgi_pass   127.0.0.1:9000;   #也可以使用sock文件与php-fpm通信fastcgi_index  index.php;fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;include        fastcgi_params;
}# /scripts 改为自己nginx网站的目录
fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
fastcgi_param  SCRIPT_FILENAME  /usr/local/nginx/html$fastcgi_script_name;

测试LNMP环境的PHP服务是否可以连接mysql

安装mysql(略)

<?php
// 数据库配置信息
$dbHost     = '127.0.0.1';
$dbUsername = 'root';
$dbPassword = 'aaa...111';
$dbName     = 'mysql';// 建立数据库连接
$link = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);// 检查连接
if (!$link) {die("连接失败: " . mysqli_connect_error());
}
echo "连接成功";// 关闭连接
mysqli_close($link);
phpinfo();
?>

nginx配置ssl证书及http跳转https

创建存放证书的文件夹

mkdir /usr/local/nginx/ssl/

生成ssl证书文件

openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/C=CN/ST=Beijing/L=Beijing/O=DevOps/CN=www.zyjngx.com"

修改nginx配置文件

http {......server {listen       80;listen       443 ssl;   #加入监听443端口配置server_name  www.zyjngx.com;# 加入ssl证书配置ssl_certificate      /usr/local/nginx/ssl/server.crt;ssl_certificate_key  /usr/local/nginx/ssl/server.key;ssl_session_timeout  5m;ssl_ciphers  HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers  on;ssl_protocols TLSv1 TLSv1.1 TLSv1.2;# 加入http跳转https配置if ($scheme = http) {return 301 https://$host$request_uri;}#charset koi8-r;#access_log  logs/host.access.log  main;# nginx连接php-fpm配置location ~ \.php$ {root           html;fastcgi_pass   127.0.0.1:9000;fastcgi_index  index.php;fastcgi_param  SCRIPT_FILENAME  /usr/local/nginx/html$fastcgi_script_name;include        fastcgi_params;}......}}

编译安装nginx后新添加模块

nginx安装使用一段时间后时因业务变更需要新加模块

注意:原来的源码包不能被删除

查看原来编译安装的命令

[root@zyj nginx-1.24.0]# nginx -V
nginx version: ABC/1.1.1
built by gcc 11.4.1 20231218 (Red Hat 11.4.1-3) (GCC) 
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module --with-http_sub_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-http_dav_module --with-http_addition_module --with-http_flv_module --with-http_mp4_module --with-pcre --with-stream

进入以前的源码包目录重新编译

cd /usr/local/src/nginx-1.24.0
#上传需要添加的模块包echo-nginx-module.zip 并解压 echo-nginx-module
[root@zyj nginx-1.24.0]# ls
auto     CHANGES.ru  configure  echo-nginx-module      html     Makefile  objs    src
CHANGES  conf        contrib    echo-nginx-module.zip  LICENSE  man       README
#停止nginx
[root@zyj nginx-1.24.0]# nginx -s stop
#重启编译
[root@zyj nginx-1.24.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module --with-http_sub_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-http_dav_module --with-http_addition_module --with-http_flv_module --with-http_mp4_module --with-pcre --with-stream --add-module=/usr/local/src/nginx-1.24.0/echo-nginx-module

执行make安装命令

注意:不要make install 否则会覆盖

[root@zyj nginx-1.24.0]# make
#替换二进制文件
[root@zyj nginx-1.24.0]# cp objs/nginx /usr/local/nginx/sbin/nginx 
cp:是否覆盖'/usr/local/nginx/sbin/nginx'? y#查看编译安装的命令
[root@zyj nginx-1.24.0]# nginx -V
nginx version: ABC/1.1.1
built by gcc 11.4.1 20231218 (Red Hat 11.4.1-3) (GCC) 
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module --with-http_sub_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-http_dav_module --with-http_addition_module --with-http_flv_module --with-http_mp4_module --with-pcre --with-stream --add-module=/usr/local/src/nginx-1.24.0/echo-nginx-module

最后一行中我们可以看到 --add-module= … 说明新加模块成功,我们重启nginx服务即可。

隐藏nginx版本号和标识

使用yum安装方式的修改配置文件,修改后不显示版本号但是相应头信息server还为nginx,无法修改http响应头的server字段值。源码安装nginx就弥补了这一缺点。

http {server_tokens     off;    #添加此行配置后再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"';access_log  /var/log/nginx/access.log  main;

源码安装的编译前要修改文件nginx.h,修改后不显示版本号,相应头信息也可不显示server为nginx

vim nginx-1.24.0/src/core/nginx.h
#改:
13 #define NGINX_VERSION      "1.24.0"
14 #define NGINX_VER          "nginx/" NGINX_VERSION
#为:
13 #define NGINX_VERSION      "1.1.1"
14 #define NGINX_VER          "ABC/" NGINX_VERSIONvim nginx-1.24.0/src/http/ngx_http_header_filter_module.c
#改:
49 static u_char ngx_http_server_string[] = "Server: nginx" CRLF;
50 static u_char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;
51 static u_char ngx_http_server_build_string[] = "Server: " NGINX_VER_BUILD CRLF;
#为:
49 static u_char ngx_http_server_string[] = "Server: ABC" CRLF;
50 static u_char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;
51 static u_char ngx_http_server_build_string[] = "Server: " NGINX_VER_BUILD CRLF;

安装好后再修改配置文件隐藏版本号

vim /usr/local/nginx/conf/nginx.conf
http {server_tokens     off;     #添加此行配置后再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"';access_log  /var/log/nginx/access.log  main;

配置nginx运行用户和cpu亲和性

vim nginx.conf
user  nginx;  #改为nginx用户
worker_processes  4; #修改进程数 有多少cpu就可以修改为多少 也可以修改为 auto 自动模式

查看进程数

[root@zyj conf]# ps aux |grep nginx
root        2677  0.0  0.0   9788  3184 ?        Ss   16:34   0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx      17790  0.0  0.1  14112  4968 ?        S    16:50   0:00 nginx: worker process
nginx      17791  0.0  0.1  14112  5096 ?        S    16:50   0:00 nginx: worker process
nginx      17792  0.0  0.1  14112  5096 ?        S    16:50   0:00 nginx: worker process
nginx      17793  0.0  0.1  14112  5096 ?        S    16:50   0:00 nginx: worker process
root       17795  0.0  0.0 221680  2304 pts/0    S+   16:50   0:00 grep --color=auto nginx

查看进程树

[root@zyj ~]# pstree -p | grep nginx|-nginx(2368)-+-nginx(2369)|             |-nginx(2370)|             |-nginx(2371)|             `-nginx(2372)

taskset -cp 查看进程可以在哪个cpu 上运行

[root@zyj ~]# taskset -cp 2369
pid 2369 的当前亲和力列表:0-3

设置亲和性

vim /usr/local/nginx/conf/nginx.conf
user  nginx;
worker_processes  4;    #设置4个进程
worker_cpu_affinity 0001 0010 0100 1000;   #加入此行将每个nginx子进程绑定到每个cpu上

重载nginx配置文件

nginx -s reload
[root@zyj ~]# pstree -p |grep nginx|-nginx(2368)-+-nginx(8270)|             |-nginx(8271)|             |-nginx(8272)|             `-nginx(8273)

查看亲和性

[root@zyj ~]# taskset -cp 8270
pid 8270 的当前亲和力列表:0

可以看到子进程已经固定到 cpu 0 上运行

优化nginx事件处理模型

常见的五种I/O模式:

  • 阻塞I/O模型
  • 非阻塞的I/O模型
  • I/O复用模型(select ,poll ,epoll)
  • 信号驱动I/O模型
  • 异步I/O模型

nginx默认采用的是IO多路复用的原理,通过异步非阻塞的时间处理机制,epoll模型,实现轻量级和高并发。

指定nginx事件处理模型

vim /usr/local/nginx/conf/nginx.conf
events {use epoll;   # 在events代码块中加入此行worker_connections 1024;
}

优化nginx最多可打开文件数

修改系统打开文件数量限制

临时配置

ulimit -SHn 65535
参数 S:表示软限制,当超过限制值会报警
参数 H:表示硬限制,必定不能超过限制值
参数 n:每个进程可以同时打开的最大文件句柄数

永久配置,需要重启生效

vim /etc/security/limits.conf
#文件最后加入
*               hard    nofile             65535
*               soft    nofile             65535

优化nginx进程最大并发连接数

vim nginx.conf
events {worker_connections  65535;    #修改events代码块中的worker_connections数值
}

worker_connections:每个工作进程可以处理并发的最大连接数。受限于内存和 linux 系统中进程最大可打开文件数。最大并发连接数=65535 * 4 (进程数)= 262,140

查看nginx进程占用的内存大小,修改连接数量后nginx进程占用内存会变高。

[root@zyj conf]# ps aux | grep nginx
root        2368  0.0  0.0   9792  3188 ?        Ss   16:52   0:00 nginx: master processnginx
nginx      26801  0.0  0.1  14116  4844 ?        S    17:17   0:00 nginx: worker process
nginx      26802  0.0  0.1  14116  4844 ?        S    17:17   0:00 nginx: worker process
nginx      26803  0.0  0.1  14116  4716 ?        S    17:17   0:00 nginx: worker process
nginx      26804  0.0  0.1  14112  4972 ?        S    17:17   0:00 nginx: worker process
root       27509  0.0  0.0 221680  2304 pts/0    S+   17:17   0:00 grep --color=auto nginx#重载配置
[root@zyj conf]# nginx -s reload[root@zyj conf]# ps aux | grep nginx
root        2368  0.0  0.0   9792  3188 ?        Ss   16:52   0:00 nginx: master processnginx
nginx      27511  3.0  0.8  40832 31360 ?        S    17:17   0:00 nginx: worker process
nginx      27512  2.0  0.8  41056 31504 ?        S    17:17   0:00 nginx: worker process
nginx      27513  2.0  0.8  40832 31488 ?        S    17:17   0:00 nginx: worker process
nginx      27514  2.0  0.8  40832 31352 ?        S    17:17   0:00 nginx: worker process
root       27516  0.0  0.0 221680  2304 pts/0    S+   17:17   0:00 grep --color=auto nginx

虚拟主机(servername)和location匹配规则

单站点设置域名访问

vim nginx.conf
server {listen       80;server_name  www.zyj.xyz;      #设置域名访问#charset koi8-r;#access_log  logs/host.access.log  main;
...
}

添加本地host文件解析

echo "192.168.3.91 www.zyj.xyz" >> /etc/hosts

重载nginx配置

nginx -s reload

访问测试

[root@zyj conf]# curl www.zyj.xyz -I
HTTP/1.1 200 OK
Server: ABC
Date: Fri, 13 Sep 2024 09:24:11 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 13 Sep 2024 08:27:38 GMT
Connection: keep-alive
ETag: "66e3f77a-267"
Accept-Ranges: bytes

虚拟主机配置

在server字段上方加入新的service字段,也可以在下方加入,与server并列即可

server {listen       80;server_name  www.zyj.cn;location / {root   /usr/local/nginx/html/cnsite/;     #新建立一个站点index  index.html index.htm;}
}

写入网站首页

mkdir -p /usr/local/nginx/html/cnsite
echo "cn-site" > /usr/local/nginx/html/cnsite/index.html

重载nginx配置

nginx -s reload

注意:不要忘记配置本地hosts文件解析

访问测试

[root@zyj conf]# curl www.zyj.cn
cn-site

常见正则表达式匹配规则表

代码说明
^匹配搜索字符串开始位置
$匹配搜索字符串结束位置
.匹配除换行符 \n 之外的任何单个字符
\转义字符,将下一个字符标记为特殊字符
[xyz]字符集,与任意一个指定字符匹配
[a-z]字符范围,匹配指定范围内的任何字符
\w与以下任意字符匹配 A-Z a-z 0-9 和下划线 , 等效于 [A-Za-z0-9_]
\d数字字符匹配,等效于 [0-9]
{n}正好匹配 n 次
{n,}至少匹配 n 次
{n,m}匹配至少 n 次至多 m 次
*零次或多次,等效于 {0,}
+一次或多次,等效于 {1,}
零次或一次,等效于 {0,1}

server_name的匹配规则

例:

server_name www.test.com localhost; # 匹配明确的域名(可以填多个,Nginx不会去验证DNS)

server_name *.test.com; # 以 *. 开头,模糊匹配

server_name www.test.; # 以 . 结尾

server_name ~^(?.+).test.com$; # 正则表达式

server_name “”; # 空字符串,不会匹配任何域名

server {listen       80;server_name  localhost;return 200 "This is 1\n";
}server {listen       80;server_name  *.test.com;return 200 "This is 2\n";
}server {listen       80 default_server;   #匹配不到规则后会使用此默认服务(default_server)server_name  "";return 200 "This is 3\n";
}

访问测试

[root@zyj ~]# curl 127.0.0.1
This is 3
[root@zyj ~]# curl localhost
This is 1
[root@zyj ~]# echo "127.0.0.1 www.test.com" >> /etc/hosts
[root@zyj ~]# curl www.test.com
This is 2
[root@zyj ~]# curl 192.168.3.91
This is 3

localtion匹配规则

Nginx 的 location 指令的基本语法如下:

location [=|~|~*|^~|@] uri { ... }
  • = 表示精确匹配。
  • ~ 表示区分大小写的正则匹配。
  • ~* 表示不区分大小写的正则匹配。
  • ^~ 表示非正则匹配,如果该选项匹配,则不再进行正则匹配。( ^ 表示“非”,~ 表示“正则”,字符意思是:不会继续匹配正则)
  • @ 定义一个命名的 location,通常用于内部重定向。

:禁止访问images文件夹下面的以php结尾的程序文件

server {listen       80;server_name  www.zyj.xyz;location / {index index.html index.htm;root html;}location ~ ^/images/.*\.(php|php5|sh|py|pl)$ {deny all;}
}

创建对应文件

[root@zyj html]# tree
.
├── 50x.html
├── images
│   ├── 1.txt
│   └── info.php
└── index.html

访问测试

[root@zyj conf]# curl www.zyj.xyz -I
HTTP/1.1 200 OK
Server: ABC
Date: Fri, 13 Sep 2024 10:13:36 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 13 Sep 2024 08:27:38 GMT
Connection: keep-alive
ETag: "66e3f77a-267"
Accept-Ranges: bytes[root@zyj conf]# curl www.zyj.xyz/images/info.php
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>[root@zyj conf]# curl www.zyj.xyz/images/1.txt
1

FastCGI缓存调优

nginx不支持对外部程序的直接调用或者解析,所有的外部程序(包括php)必须通过fastcgi接口来调用。fastcgi接口在linux下是socket,(这个socket可以是文件socket,也可以是ip socket)。为了调用cgi程序,还需要一个fastcgi的wrapper(wrapper可以理解为用于启动另一个程序的程序),这个wrapper绑定在某个固定socket上,如端口或者文件socket。当nginx将cgi请求发送给这个socket的时候,通过fastcgi接口,wrapper接纳到请求,然后派生出一个新的线程,这个线程调用解释器或者外部程序处理脚本并读取返回数据;接着,wrapper再将返回的数据通过fastcgi接口,沿着固定的socket传递给nginx;最后,nginx将返回的数据发送给客户端,这就是nginx+fastcgi的整个运作过程。

如果使用FastCGI(如与PHP-FPM配合),可以使用fastcgi_cache指令启用缓存。

http {# 定义FastCGI缓存区域fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=my_cache:512m max_size=4g inactive=60m;fastcgi_connect_timeout 300;fastcgi_send_timeout 300;fastcgi_read_timeout 300; fastcgi_buffer_size 64k;fastcgi_buffers 4 64k;fastcgi_busy_buffers_size 128k;fastcgi_temp_file_write_size 128k;fastcgi_temp_path /var/run/nginx-tmp-cache;server {listen       80;server_name  www.zyj92.com;location / {index index.html index.htm;root /usr/share/nginx/html;}location ~ \.php$ {root           /usr/share/nginx/html;index  index.html index.htm;fastcgi_pass   unix:/run/php-fpm/www.sock; #使用scoket通信#;listen = /run/php-fpm/www.sock 注意修改php-fpm配置文件/etc/php-fpm.d/www.conf#;listen = 127.0.0.1:9000  # 也可以修改为ip和端口通信 注:fastcgi_pass也要修改了#unix:/run/php-fpm/www.sock;  # php-fpm 默认配置 为 socket交互fastcgi_index  index.php;fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;include        fastcgi_params;include        fastcgi.conf;fastcgi_cache_valid 200 302 1h; fastcgi_cache_valid 301 1d; fastcgi_cache_valid any 1m;fastcgi_cache my_cache;  # 使用定义的缓存区域fastcgi_cache_key $host$request_uri;  # 定义缓存键(key)fastcgi_cache_min_uses 1;     # 请求1次就会被缓存fastcgi_cache_use_stale error timeout invalid_header http_500; #500状态码不缓存}}}

解释:
inactive=60 代表如果缓存文件60m内没有被访问,则删除。
max_size=代表缓存最大为4G
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=my_cache:10m inactive=60m;
/var/run/nginx-cache: 缓存文件的存储路径。
levels=1:2: 缓存目录的层次结构,这里表示首先按第一个字符分目录,然后在这些目录中再按前两个字符分目录。
keys_zone=my_cache:512m: 为缓存区命名(这里是 my_cache)并设置其大小(这里是 512m)。
inactive=60m: 缓存项在不被访问后多久被视为“非活动”的,之后它们可以被清理器线程删除。
fastcgi_connect_timeout指定连接到后端fastcgi的超时时间。
fastcgi_send_timeout指定向fastcgi传送请求的超时时间,这个值是已经完成两次握手后向fastcgi传送请求的超时时间。
fastcgi_buffer_size用于指定读取fastcgi应答第一部分需要用多大的缓冲区,这个值表示将使用1个64kb的缓冲区读取应答的第一部分(应答头),可以设置为fastcgi_buffers选项指定的缓冲区大小。
fastcgi_buffers指定本地需要用多少和多大的缓冲区来缓冲fastcgi的应答请求。如果一个php脚本所产生的页面大小为256kb,那么会为其分配4个64kb的缓冲区来缓存;如果页面大小大于256kb,那么大于256kb的部分会缓存到fastcgi_temp指定的路径中,但是这并不是好方法,因为内存中的数据处理速度要快于硬盘。一般这个值应该为站点中php脚本所产生的页面大小的中间值,如果站点大部分脚本所产生的页面大小为256kb,那么可以把这个值设置为“16 16k”、“4 64k”等。
fastcgi_busy_buffers_size的默认值是fastcgi_buffers的两倍。
fastcgi_temp_file_write_size表示在写入缓存文件时使用多大的数据块,默认值是fastcgi_buffers的两倍。
启用fastcgi缓存并为其命名是指fastcgi_cache的作用。开启缓存非常有用,可以有效降低cpu的负载,并且防止502错误的发生,但是开启缓存也会引起很多问题,要视具体情况而定。
fastcgi_cache_valid、fastcgi用来指定应答代码的缓存时间,实例中的值表示将200和302应答缓存一个小时,将301应答缓存1天,其他应答均缓存1分钟。

创建对应index.php文件,访问测试index.php 页面 查看目录下是否有缓存文件生成

echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/index.php
cd /var/run/nginx-cache/
[root@www nginx-cache]# tree
.
└── d└── 51└── 2c14e3b03f375b82302c36969995d51d2 directories, 1 file

将缓存的目录挂载到内存,提高文件i/o读写速度。

vim /etc/fstab
#文件最后加入
tmpfs /var/run/nginx-cache tmpfs defaults,size=512m    0    0

重载配置并挂载

systemctl daemon-reload
mount -a
df -Th
文件系统                    类型       容量  已用   可用  已用% 挂载点
devtmpfs                  devtmpfs  4.0M     0  4.0M    0% /dev
tmpfs                     tmpfs     1.9G     0  1.9G    0% /dev/shm
tmpfs                     tmpfs     777M  9.2M  768M    2% /run
/dev/mapper/rl_bogon-root xfs        50G  3.7G   47G    8% /
/dev/mapper/rl_bogon-home xfs        25G  207M   25G    1% /home
/dev/nvme0n1p2            xfs       960M  223M  738M   24% /boot
/dev/nvme0n1p1            vfat      599M  7.1M  592M    2% /boot/efi
tmpfs                     tmpfs     389M  4.0K  389M    1% /run/user/0
tmpfs                     tmpfs     512M   64K  512M    1% /run/nginx-cache

当访问php页面后,生成的缓存会挂载到内存中,再次访问后会从内存中读取

tmpfs                     tmpfs     512M   64K  512M    1% /run/nginx-cache

开启高效传输模式

在nginx配置中把sendfile改为on

vim /usr/local/nginx/conf/nginx.conf
sendfile        on;

默认情况文件传输需要经过 User space,开启高效文件传输模式后则直接在 Kernel space 进行传输

开启gzip压缩

压缩可以减少数据传输量,提高响应速度。

首先,确保在Nginx中启用了Gzip模块。这通常是通过在nginx.conf文件的http块中添加以下指令来完成的

vim /usr/local/nginx/conf/nginx.conf
http {gzip on;  # 启用Gzip压缩 将原来gzip on;前的#号注释删除
}

在gzip on; 后加入

gzip on;
gzip_vary on;
gzip_min_length 1k;
gzip_comp_level 6;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml image/jpeg image/gif image/png;
  • gzip_min_length 1k:设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取,默认值是0,不管页面多大都进行压缩,建议设置成大于1K,如果小与1K可能会越压越大。
  • gzip_buffers 4 32k:压缩缓冲区大小,表示申请4个单位为32K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。
  • gzip_http_version 1.1:压缩版本,用于设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持GZIP解压,使用默认即可。
  • gzip_comp_level 6:压缩比例,用来指定GZIP压缩比,1压缩比最小,处理速度最快,9压缩比最大,传输速度快,但是处理慢,也比较消耗CPU资源。
  • gzip_types text/css text/xml application/javascript:用来指定压缩的类型,‘text/html’类型总是会被压缩。默认值: gzip_types text/html (默认不对js/css文件进行压缩)压缩类型,匹配MIME型进行压缩;

curl 命令校验时需要指定你要测试的文件

[root@zyj ~]# curl -I -H "Accept-Encoding: gzip, deflate" www.zyj91.com/images/g3.jpg
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Sun, 15 Sep 2024 08:10:05 GMT
Content-Type: image/jpeg
Last-Modified: Sat, 27 Feb 2016 05:17:08 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: W/"56d13154-738d"
Content-Encoding: gzip  #启用了gzip压缩

expires浏览器缓存调优

缓存,主要针对于图片,css,js等元素更改机会比较少的情况下使用,特别是图片,占用带宽大,我们完全可以设置图片在浏览器本地缓存365d,css,js,html可以缓存个10来天,这样用户第一次打开加载慢一点,第二次,就非常快了!缓存的时候,我们需要将需要缓存的拓展名列出来, Expires缓存配置在server字段里面。

vim /usr/local/nginx/conf/nginx.conf
#根据文件名称进行缓存
location ~* \.(ico|jpeg|gif|png|jpeg|bmp|swf|flv)$
{expires 30d;  #过期时间为30天log_not_found off;access_log off;
}location ~* \.(js|css)$ 
{expires 7d;log_not_found off;access_log off;
}location ~* \.(htm|html)$ 
{expires 7d;log_not_found off;access_log off;
}#根据目录进行缓存
location ~ ^/(images|javascript|js|css|flash|media|static)/ {expires 30d;  #过期时间为30天
}

注:log_not_found off;是否在error_log中记录不存在的错误。默认是。

访问测试

[root@www ~]# date
2024年 09月 16日 星期一 15:49:53 CST
[root@www ~]# curl -I -H "Accept-Encoding: gzip, deflate" www.zyj92.com/images/g3.jpg
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Mon, 16 Sep 2024 07:49:56 GMT
Content-Type: image/jpeg
Last-Modified: Sat, 27 Feb 2016 05:17:08 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: W/"56d13154-738d"
Expires: Wed, 16 Oct 2024 07:49:56 GMT
Cache-Control: max-age=2592000
Content-Encoding: gzip#启用了expire缓存,缓存时间为30天
Expires: Wed, 16 Oct 2024 07:49:56 GMT

禁止使用ip地址访问网站

指定 default server 禁止ip 访问,禁止不匹规则的访问。

vim /usr/local/nginx/conf/nginx.conf
server {listen       80;server_name  default_server;return 403;
}

设置301永久跳转

www.zyj91.com跳转至www.zyj91.xyz

vim /usr/local/nginx/conf/nginx.conf
    server {listen       80;server_name  default_server;return 403;}server {listen       80;server_name www.zyj91.xyz;  location / {root   /usr/local/nginx/html/xyz-site; #创建需要跳转至新网站的目录及页面文件index  index.html index.htm;}}server {listen       80;server_name  www.zyj91.com;if ($host = 'www.zyj91.com') {rewrite ^/(.*)$ http://www.zyj91.xyz/$1 permanent;}location / {root   html;index  index.html index.htm;}}

访问测试

[root@zyj xyz-site]# curl www.zyj91.com
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.24.0</center>
</body>
</html>[root@zyj xyz-site]# curl www.zyj91.com -L
xyz-site站点

防盗链设置

禁止其他网站盗用你的网站图片等资源

查看日志发现有http://www.badreq.com/访问我的nginx服务器

cat /usr/local/nginx/logs/access.log
192.168.3.1 - - [15/Sep/2024:17:27:08 +0800] "GET /images/img2.jpg HTTP/1.1" 200 32575 "http://www.badreq.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0" "-"

这时候我们需要禁止referers 为http://www.badreq.com/的访问请求

vim /usr/local/nginx/conf/nginx.conf
location ~* \.(jpg|jpeg|png|gif|bmp|swf|flv|mp4|mp3|wav|wma|wmv|zip|rar|gz|bz2|pdf|doc|docx|xls|xlsx|ppt|pptx) {valid_referers none blocked *.zyj91.com;if ($invalid_referer) {return 403;}
}

让我们来拆解一下这段配置:

  • location ~* \.(jpg|jpeg|png|gif|bmp|swf|flv|mp4|mp3|wav|wma|wmv|zip|rar|gz|bz2|pdf|doc|docx|xls|xlsx|ppt|pptx):这部分表示匹配以指定扩展名的文件。
  • valid_referers none blocked *.yourdomain.com;:这里定义了合法的 Referer 来源。none 表示没有 Referer 头的请求是合法的,blocked 表示 Referer 头被防火墙或者代理服务器隐藏的请求是合法的,*.yourdomain.com 表示来自您自己域名下的请求是合法的。
  • if ($invalid_referer) { return 403; }:如果 Referer 不合法,就返回 403 禁止访问的状态码。

限制连接数

为了避免单个客户端占用过多资源,可以限制每个客户端的连接数。

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

http字段中配置:

limit_conn_zone $binary_remote_addr zone=mylimit:10m;

server的location 字段配置:

limit_conn mylimit 5;  # 每个IP地址最多允许5个同时连接

nginx日志切割

编写log_cut.sh日志切割脚本

vim /usr/local/nginx/logs/log_cut.sh
#!/bin/bash
date=$(date +%F -d -1day)  #一天前的日期
cd /usr/local/nginx/logs
if [ ! -d bak ] ; then
mkdir -p bak
fi
mv access.log bak/access_$date.log
mv error.log bak/error_$date.log
/usr/local/nginx/sbin/nginx -s reopen
tar -jcvf bak/$date.tar.bz2 bak/access_$date.log bak/error_$date.log
find /usr/local/nginx/logs/bak -mtime +90 -name "*.bz2" -exec rm -rf {} \;
rm -rf bak/*.log

添加执行权限

chmod +x /usr/local/nginx/logs/log_cut.sh

添加计划任务

crontab -e
#末尾加入
0 1 * * * /bin/sh /usr/local/nginx/logs/log_cut.sh > /dev/null 2>&1

修改nginx配置文件取消注释启用日志记录

vim /usr/local/nginx/conf/nginx.conf
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;

其中,各个字段的含义如下:

  1. r e m o t e a d d r :与 remote_addr: 与 remoteaddr:与http_x_forwarded_for 用以记录客户端的 ip 地址;
  2. $remote_user:用来记录客户端用户名称;
  3. $time_local: 用来记录访问时间与时区;
  4. $request: 用来记录请求的 url 与 http 协议;
  5. $status: 用来记录请求状态,成功是 200;
  6. $body_bytes_sent:记录发送给客户端文件主体内容大小;
  7. $http_referer:用来记录从哪个页面链接访问过来的;
  8. $http_user_agent:记录客户端浏览器的相关信息;
    KaTeX parse error: Expected group after '_' at position 118: ….log bak/access_̲date.log
    mv error.log bak/error_ d a t e . l o g / u s r / l o c a l / n g i n x / s b i n / n g i n x − s r e o p e n t a r − j c v f b a k / date.log /usr/local/nginx/sbin/nginx -s reopen tar -jcvf bak/ date.log/usr/local/nginx/sbin/nginxsreopentarjcvfbak/date.tar.bz2 bak/access_KaTeX parse error: Expected group after '_' at position 19: …e.log bak/error_̲date.log
    find /usr/local/nginx/logs/bak -mtime +90 -name ".bz2" -exec rm -rf {} ;
    rm -rf bak/
    .log

添加执行权限```shell
chmod +x /usr/local/nginx/logs/log_cut.sh

添加计划任务

crontab -e
#末尾加入
0 1 * * * /bin/sh /usr/local/nginx/logs/log_cut.sh > /dev/null 2>&1

修改nginx配置文件取消注释启用日志记录

vim /usr/local/nginx/conf/nginx.conf
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;

其中,各个字段的含义如下:

  1. r e m o t e a d d r :与 remote_addr: 与 remoteaddr:与http_x_forwarded_for 用以记录客户端的 ip 地址;
  2. $remote_user:用来记录客户端用户名称;
  3. $time_local: 用来记录访问时间与时区;
  4. $request: 用来记录请求的 url 与 http 协议;
  5. $status: 用来记录请求状态,成功是 200;
  6. $body_bytes_sent:记录发送给客户端文件主体内容大小;
  7. $http_referer:用来记录从哪个页面链接访问过来的;
  8. $http_user_agent:记录客户端浏览器的相关信息;

http://www.mrgr.cn/news/31258.html

相关文章:

  • 力扣题解(统计特殊整数)
  • 使用adb命令进行内存测试
  • Jenkins自动化部署后端项目看这篇就够了
  • 万魔头戴式耳机怎么样?万魔、西圣、JBL三款旗舰机型激战评测!
  • Vue 修饰符 | 指令 区别
  • 【秋招笔试】09.20-58同城秋招(已改编)-三语言题解
  • Python基础
  • Python教你用20行代码做一个骰子模拟博弈游戏
  • Rocprofiler测试
  • Redis-01 入门和十大数据类型
  • 2024年8月月终总结
  • 初探哲学世界
  • 24.9.2-24.9.20第一次周总结
  • 数据处理与统计分析篇-day07-Pandas数据拼接与空值处理
  • 智能新时代,游戏盾守护顺畅体验
  • HarmonyOS 应用获取公钥和 MD5 指纹签名信息
  • 如何将 JxBrowser 添加到 Maven 项目中
  • 利士策分享,周末时光:一场自我充实的精致规划
  • mybatisplus中id生成策略
  • 【Android源码】屏蔽系统通知出现在系统栏中