nginx模块安装
2022年5月31日大约 2 分钟约 502 字
模块
Nginx官方模块
第三方模块
在使用nginx -V
命令时,显示的--with-*
开头的是编译的模块
http_stub_status_module
用户展示客户端连接的状态,用于监控当前连接信息
# >>> vim /etc/nginx/conf.d/default.conf
# 该模块需要在 server或location下配置
server {
#...
location /mystatus {
stub_status;
}
}
# 通过访问url /mystatus可以得到当前链接数
# http://*.*.*.*/mystatus
Active connections: 2 # 当前活跃的连接数
server accepts handled requests
396 396 1293 # 接收握手总次数 处理的连接数 总请求数
Reading:0 Writing: 1 Waiting: 1 # 正在读 正在写 正在等待(长连接情况下的空闲)
http_random_index_module
目录中选择一个随机主页
# >>> vim /etc/nginx/conf.d/default.conf
# 该模块需要在location下配置
server {
#...
location / {
root /usr/share/nginx/html;
random_index on;
#index index.html index.htm;
}
}
# 在/usr/share/nginx/html/目录下创建多个html文件,就可以随机访问页面
http_sub_module
HTTP内容替换
sub_filter_last_modified
作用:请求时,检查服务端内容是否变更,将时间信息放入HTTP头部。如果没有更新内容就不需要返回内容(缓存)
语法: sub_filter_last_modified on;
该语法在http、server、location下配置
sub_filter_once
作用:匹配第一个还是匹配所有
语法:sub_filter_once off;
该语法在http、server、location下配置
sub_filter
作用:替换html内指定字符串
语法:sub_filter string replacement;
该语法在http、server、location下配置
# >>> vim /etc/nginx/conf.d/default.conf
# 该模块需要在location下配置
server {
#...
location / {
root /usr/share/nginx/html;
index index.html index.htm;
sub_filter '<a>imooc' '<a>IMOOC';
sub_filter_once off; # 全局替换
}
}
高级模块
geoip_module模块
基于IP地址匹配MaxMind GeoIP 二进制文件,读取IP所在地域信息
安装:
# 安装模块
yum install nginx-module-geoip
# 查看
ls /etc/nginx/modules/
# vim nginx.conf
load_module "modules/ngx_http_geoip_module.so";
load_module "modules/ngx_stream_geoip_module.so";
# 下载ip数据库
cd /etc/nginx/geoip
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
# 解压
gunzip GeoIP.dat.gz GeoLiteCity.dat.gz
#>>> vim /etc/nginx/conf.d/test_geo.conf
geoip_country /etc/nginx/geoip/GeoIP.dat;
geoip_city /etc/nginx/geoip/GeoLiteCity.dat;
server {
listen 80;
server_name localhost;
location / {
if ($geoip_country_code != CN) {
return 403;
}
root /usr/share/nginx/html;
index index.html index.htm;
}
# 测试客户端IP地理位置
location /myip {
default_type text/plain;
return 200 "$remote_addr $geoip_country_name $geoip_country_code $geoip_city";
}
}