nginx配置(二)

nginx 版本信息、http_core_module

自定义 nginx 版本信息

  1. 如果想自定义响应报文的nginx版本信息,需要修改源码文件,重新编译
  2. 如果server_tokens on,修改 src/core/nginx.h 修改第13-14行,如下示例
    #define NGINX_VERSION “1.68.9”
    #define NGINX_VER “wanginx/” NGINX_VERSION
  3. 如果server_tokens off,修改 src/http/ngx_http_header_filter_module.c
    第49行,如下示例:
    static char ngx_http_server_string[] = “Server: nginx” CRLF;
    把其中的nginx改为自己想要的文字即可,如:wanginx

ngx_http_core_module

tcp_nodelay on | off;  // 在keepalived模式下的连接是否启用TCP_NODELAY选项,即Nagle算法. 当为off时,延迟发送,每发送一个包就需要确认ACK,才发送下一个包;默认On时,不延迟发送,多个包才确认一次
tcp_nopush on | off ; // 在开启sendfile,on时合并响应头和数据体在一个包中一起发送
sendfile on | off; // 是否启用sendfile功能,在内核中封装报文直接发送,默认Off
charset charset | off; //是否在响应报文中的Content-Type显示指定的字符集,默认off不显示
server_tokens on | off | build | string; // 是否在响应报文的Server首部显示nginx版本
// 与套接字相关的配置:
 server { ... }
 // 配置一个虚拟主机
 server {
 	listen address[:PORT]|PORT|unix:/PATH/TO/SOCKET_FILE;
 	server_name SERVER_NAME;
 	root /PATH/TO/DOCUMENT_ROOT;
 }

listen port;

 default_server  // 设定为默认虚拟主机,无法匹配虚拟主机时使用
 ssl //限制仅能够通过ssl连接提供服务
backlog=number //超过并发连接数后,新请进入后援队列的长度
 rcvbuf=size 接收缓冲区大小
sndbuf=size 发送缓冲区大小
(1) 基于port;
listen PORT; 指令监听在不同的端口
(2) 基于ip的虚拟主机
listen IP:PORT; IP 地址不同
(3) 基于hostname server_name fqdn; 指令指向不同的主机名

server_name name ...;

虚拟主机的主机名称后可跟多个由空白字符分隔的字符串
(1)  支持*通配任意长度的任意字符
server_name *.magedu.com www.magedu.*
(2) 支持~起始的字符做正则表达式模式匹配,性能原因慎用
 server_name ~^www\d+\.magedu\.com$
说明: \d 表示 [0-9]
(3)  匹配优先级机制从高到低
a  首先是字符串精确匹配 如www.magedu.com 
b 左侧*通配符 如:*.magedu.com
c 右侧*通配符 如:www.magedu.*
d 正则表达式 如: ~^.*\.magedu\.com$
e default_server

新建一个 pc web 站点

// 主配置文件 /etc/ntinx/nginx.conf中的 httpd{ include /etc/nginx/conf.d/*.conf; }

cd /etc/nginx/conf.d/
vim pc.conf
server {
    listen 80;
    server_name www.pc.com;
    location / {
        root /data/pc;
    }
}
mkdir /data/pc
echo pc web > /data/pc/index.html

新建一个 mobile web 站点

vim mobile.conf
server {
    listen 80;
    server_name www.mobile.com;
    location / {
        root /data/mobile;
    }
}
mkdir /data/mobile
echo mobile web > /data/mobile/index.html
nginx -s reload

root、alias、location、access、auth_basic

root 与 alias

vim pc.conf
server {
    listen 80;
    server_name www.pc.com;
    location / {
        root /data/pc;
    }
    location /about {   // 根目录为 /data/pc/about
        root /data/pc;
        index index.html;
    }
}
mkdir /data/pc/about
echo about > /data/pc/about/index.html
nginx -s reload
server {
    listen 80;
    server_name www.pc.com;
    location / {
        root /data/pc;
    }
    location /about {
        #root /data/pc;
        index index.html;
        alias /data/pc; //访问 www.pc.com/about ->/data/pc/index.html
    }
}

location 的详细使用

语法:location = [=|~|~*|^~] /uri/ { … }

  1. = 对URI做精确匹配;
  2. ^~ 对URI的最左边部分做匹配检查,不区分字符大小写
  3. ~ 对URI做正则表达式模式匹配,区分字符大小写
  4. ~* 对URI做正则表达式模式匹配,不区分字符大小写
  5. 不带符号 匹配起始于此uri的所有的uri
  6. \ 转义符,可将 . * ?等转义为普通符号
  7. 匹配优先级从高到低: =, ^~, ~/~*, 不带符号

nginx 四层访问控制
基于模块 ngx_http_access_module实现,可以通过匹配客户端源ip地址进行限制。

server {
	listen 80;
	location /about {
		alias /data/nginx/html;
		index index.html;
		deny 192.168.43.1;
		allow 192.168.43.7;
		deny all;
	}
}

nginx 账户认证功能

htpasswd -cmb .user_passwd zhangsan 123
htpasswd -mb .user_passwd lisi 456

vim /etc/nginx/conf.d/auth.conf
server {
        listen 80;
        server_name www.xuepeng.com;
        location /login {
                alias /data/auth;
                index index.html;
                auth_basic "login password";
                auth_basic_user_file /etc/nginx/conf.d/.user_passwd;
        }
}
mkdir /data/auth
echo auth > /data/auth/index.html
nginx

error_page、try_files、keepalive、autoindex

自定义错误页面

server {
	listen 80;
	server_name www.xuepeng.com;
	error_page 500 502 503 504 404 /error.html;
	location = /error.html {
		root /data/error;
	}
}

检测文件是否存在

server {
        listen 80;
        server_name www.xuepeng.com;
        location /try_files {
                root /data;
                try_files $uri $uri/index.html $uri.html =489;
        }
}

长连接配置

server {
        listen 80;
        server_name www.xuepeng.net;
        root /data/keepalived;
        keepalive_timeout 65 56;
        keepalive_requests 3;
}

作为下载服务器配置

server {
        listen 80;
        server_name www.xuepeng.org;
        location /download {
                autoindex on; # 自动索引功能
                autoindex_exact_size on;# 计算文件确切大小(单位bytes),off只显示大概大小(单位kb、mb、gb)
                autoindex_localtime on;# 显示本机时间而非GMT(格林威治)时间
                limit_rate 10k; # 限制响应给客户端的传输速率,一个连接的速率,单位是bytes/second,默认值0表示无限制
                # autoindex_format json;
                root /data;
        }
}

curl -X OPTIONS websrv 查看web服务器支持客户端用什么请求方法

location /about {
	limit_except GET {  // 限制客户端使用除了get之外的其它方法
		allow 192.168.43.1;
		deny all;	
	}
}

文件操作优化的配置

location /video {
	sendfile on;
	aio on;   // 开启异步io
	directio 8m;  // 当文件大于等于8m时,直接写磁盘,而非写缓存
}
open_file_cache on|off; // 缓存
open_file_cache max=N  [inactive=time] //有多少个缓存,缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于 open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项,将被删除
open_file_cache_errors on | off; // 是否缓存查找时发生错误的文件一类的信息,默认值为off
open_file_cache_min_uses number; //open_file_cache指令的inactive参数指定的时长内,至少被命中此处指定的次数方可被归类为活动项,默认值为1
open_file_cache_valid time; // 缓存项有效性的检查频率,默认值为60s

stub_status、echo-nginx-module、variable、log、favicon.ico

nginx 状态页

server {
        listen 80;
        server_name www.xuepeng.aa;
        root /data;
        location = /nginx_status {
                stub_status;
                allow 192.168.43.0/24;
                deny all;
        }
}

ngx_http_stub_status_module模块
用于输出nginx的基本状态信息, 输出信息示例:
Active connections: 291
server accepts handled requests #下面三个数分别对应accepts,handled,requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
Active connections:当前状态,活动状态的连接数
accepts:统计总值,已经接受的客户端请求的总数
handled:统计总值,已处理完成的客户端请求总数,一般和accepts相同,除非拒绝
requests:统计总值,客户端发来的总的请求数
Reading:当前状态,正在读取客户端请求报文首部的连接的连接数
Writing:当前状态,正在向客户端发送响应报文过程中的连接数
Waiting:当前状态,正在等待客户端发出请求的空闲连接数

nginx第三方模块 echo-nginx-module

yum install git –y
cd /usr/local/src
git clone https://github.com/openresty/echo-nginx-module.git
cd nginx-1.16.1/
useradd -r -s /sbin/nologin nginx
yum install gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed -y
./configure --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_perl_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=/usr/local/src/echo-nginx-module
make -j `lscpu|awk '/^CPU\(s\)/{print $2}'` && make install
chown -R nginx.nginx /apps/nginx/
ln -s /apps/nginx/sbin/nginx /usr/sbin/
server {
        listen 80;
        server_name www.xuepeng.com;
        location /test {
                default_type text/plain;
                echo $remote_addr;
        }
}
vim /apps/nginx/conf/conf.d/pc.conf
location /test {
	index index.html;
	default_type text/html;
	echo "hello world,main-->";
	echo_reset_timer;
	echo_location /sub1;
	echo_location /sub2;
	echo "took $echo_timer_elapsed sec for total.";
}
location /sub1 {
	echo_sleep 1;
	echo sub1;
}
location /sub2 {
	echo_sleep 1;
	echo sub2;
}

nginx 变量使用

  1. nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用,变量可以分为内置变量和自定义变量,内置变量是由nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值
  2. 常见内置变量
    $remote_addr;#存放了客户端的地址,注意是客户端的公网IP
    $args;#变量中存放了URL中的指令
    $document_root;#保存了针对当前资源的请求的系统根目录
    $cookie_ name ; #表示key为 name 的cookie值
    $document_uri;#保存了当前请求中不包含指令的URI,注意是不包含请求的指
    $host;#存放了请求的host名称
    $http_user_agent;#客户端浏览器的详细信息
    $http_cookie;#客户端的cookie信息
    $limit_rate;#如果nginx服务器使用limit_rate配置了显示网络速率,则会显示,如果没有设置, 则显示0
    $remote_port;#客户端请求Nginx服务器时客户端随机打开的端口
    $remote_user;#已经经过Auth Basic Module验证的用户名
    $request_body_file;#做反向代理时发给后端服务器的本地资源的名称
    $request_method;#请求资源的方式,GET/PUT/DELETE等
    $request_filename;#当前请求的资源文件的路径名称,由root或alias指令与URI请求生成的文件绝对路径,如/apps/nginx/html/main/index.html
    $request_uri;#包含请求参数的原始URI,不包含主机名。如:main/index.do?id=090&partner=search。
    $scheme;#请求的协议,如ftp,https,http等
    $server_protocol;#请求资源的协议版本,如HTTP/.0,HTTP/.,HTTP/.0等
    $server_addr;#保存了服务器的IP地址
    $server_name;#请求的服务器的主机名
    $server_port;#请求的服务器的端口
  3. 自定义变量
    set $variable value;
    示例:
    set $name magedu;
    echo $name;
    set $my_port $server_port;
    echo m y p o r t ; e c h o " my_port; echo " server_name:$server_port";

nginx 日志
Syntax: log_format name [escape=default|json|none] string …;
Default: log_format combined “…”;
Context: http

log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

json类型的日志

log_format access_json '{"@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",'
'"uri":"$uri",'
'"domain":"$host",'
'"xff":"$http_x_forwarded_for",'
'"referer":"$http_referer",'
'"tcp_xff":"$proxy_protocol_addr",'
'"http_user_agent":"$http_user_agent",'
'"status":"$status"}';

应用日志
在这里插入图片描述

注意

  1. 用命令 rm -rf logfie,如果没有重启或重新加载 nginx服务,日志文件是不会生成的。
  2. 应该用命令 > logfile ,日志内容被清空,但日志文件还在
  3. cat /dev/null > /data/log/test.log 这个命令更通用

日志缓存
open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;
缓存各日志文件相关的元数据信息
max:缓存的最大文件描述符数量
min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项
inactive:非活动时长
valid:验证缓存中各缓存项是否为活动项的时间间隔

关于favicon.ico

  1. favicon.ico 文件是浏览器收藏网址时显示的图标,当使用浏览器访问页面时,浏览器会自己主动发起请求获取页面的favicon.ico文件,但是当浏览器请求的favicon.ico文件不存在时,服务器会记录404日志,而且浏览器也会显示404报错
  2. 服务器不记录访问日志:
location = /favicon.ico {
	log_not_found off; #文件没发现事件不记录error_log
	access_log off;  #不记录access_log
}
将图标保存到指定目录访问:
#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
root /data/nginx/html/pc/images;
}
发布了61 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/studywinwin/article/details/104210630
今日推荐