文章目录
Nginx基础配置一
博客后续可看Nginx基础配置二
1. nginx 简介
Nginx(发音为"engine-x")是一款高性能的开源Web服务器和反向代理服务器。它由俄罗斯的程序员Igor Sysoev开发,于2004年首次发佈。Nginx的设计目标是解决C10k问题,即同时处理成千上万个并发连接的能力。
Nginx以其出色的性能和高度的可伸缩性而闻名。它採用事件驱动的架构和异步非阻塞的处理方式,能够在相对较低的硬件配置下处理大量的并发连接。这使得Nginx在面对高流量负载时表现出色,并且能够有效地处理静态内容、动态内容和反向代理等场景。
除了作为Web服务器,Nginx还可以用作反向代理服务器。反向代理是一种服务器架构模式,它通过代理服务器接收客户端请求,并将请求转发给后端服务器。这种架构可以提供负载均衡、高可用性和安全性等优势。Nginx具有强大的反向代理功能,可以根据配置规则将请求转发到不同的后端服务器,并灵活地处理各种网络通信协议。
此外,Nginx还支持许多其他功能和模块,包括SSL/TLS加密、虚拟主机配置、URL重写、访问控制、日志记录和gzip压缩等。它还具有简单的配置语法和灵活的配置选项,使得管理员能够轻松地进行定制和扩展。。
2. nginx的特性与优点
2.1 nginx的特性
- 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
- 使用epoll and kqueue作为开发模型
- nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
- nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多
2.2 nginx的优点
- 高性能:Nginx具有出色的性能,能够处理大量并发连接和高流量负载。
- 轻量级:Nginx的设计精简,佔用系统资源较少,在低配置服务器上表现出色。
- 反向代理和负载均衡:Nginx可以作为反向代理服务器,将请求分发给多个后端服务器,并实现负载均衡,提高系统的可扩展性和稳定性。
- 静态文件服务:Nginx能够快速地提供静态文件服务,如HTML、CSS、JavaScript和图像等,提高网站的响应速度。
- 高度可靠:Nginx的架构稳定,具备故障恢复能力,能够持久提供稳定的服务。
- 热部署和动态模块加载:Nginx支持热部署,可以动态加载配置文件和模块,无需重启服务器。
- 强大的URL重写和重定向:Nginx提供灵活的URL重写和重定向功能,方便管理网站的URL结构和实现页面跳转。
- SSL/TLS支持:Nginx内置的SSL/TLS支持使得可以安全地进行加密通信,保护敏感数据的安全性。
- 可扩展性:Nginx具备良好的可扩展性,能够处理大规模流量和请求。
- 社区支持和广泛应用:Nginx拥有活跃的社区支持,有大量的用户和开发者,广泛应用于各种场景,包括网站、应用服务器、缓存服务器等。
3. nginx的功能及应用类别
3.1 nginx的基本功能
- 静态文件服务:提供快速且有效的静态文件(如HTML、CSS、JavaScript、图像等)的传递。
- 反向代理:将客户端的请求转发到后端的多个服务器,实现负载均衡和高可用性。
- 负载均衡:将流量分发给多个后端服务器,平衡服务器的负载。
- 支持FastCGI(fpm,LNMP),uWSGI(Python)等
- 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
- SSL/TLS加密:支持配置和管理SSL/TLS协议,提供安全的通信通道。
3.2 nginx的扩展功能
- 基于名称和IP的虚拟主机
- 支持keepalive
- 支持平滑升级
- 定制访问日志、支持使用日志缓冲区提高日志存储性能
- URL重写和重定向:修改URL结构或将请求重定向到其他地址。
- 支持路径别名
- 支持基于IP及用户的访问控制
- 支持速率限制,支持并发数限制
3.3 nginx的应用类别
- 使用nginx结合FastCGI运行PHP、JSP、Perl等程序
- 使用nginx作反向代理、负载均衡、规则过滤
- 使用nginx运行静态HTML网页、图片
- nginx与其他新技术的结合应用
4. nginx的模块与工作原理
nginx
由内核和模块组成。其中,内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location block(location是nginx配置中的一个指令,用于URL匹配),而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。
4.1 nginx的模块分类
Nginx的模块是用于扩展和定制Nginx服务器功能的组件。以下是一些常见的Nginx模块的简介:
- 核心模块(Core Modules):提供基本的核心功能,包括处理HTTP请求和事件驱动等。常见的核心模块包括ngx_http_core_module和ngx_events_module。
- HTTP模块(HTTP Modules):实现与HTTP协议相关的功能,如反向代理、负载均衡、URL重写、SSL/TLS支持等。常见的HTTP模块有ngx_http_proxy_module、ngx_http_ssl_module和ngx_http_rewrite_module等。
- 第三方模块(Third-Party Modules):由第三方开发者提供的扩展模块,可以增加额外的功能和特性。例如,lua-nginx-module提供了对Lua脚本的支持,geoip-nginx-module提供了对IP地理位置查询的支持。
- 动态模块(Dynamic Modules):Nginx 1.9.11及以上版本引入了动态模块的支持。动态模块可以在不重新编译Nginx的情况下添加或删除功能模块。
- 附加模块(Additional Modules):由Nginx官方提供的一些额外的模块,包括mail模块(用于邮件代理)和stream模块(用于TCP/UDP代理)等。
- 缓存模块(Caching Modules):用于实现静态资源的缓存功能,加速网站的访问速度。常见的缓存模块有ngx_http_proxy_cache_module和ngx_http_fastcgi_cache_module等。
- 安全模块(Security Modules):提供安全性相关的功能,如请求限速、连接限速、访问控制等。常见的安全模块有ngx_http_limit_req_module和ngx_http_limit_conn_module等。
4.2 nginx的工作原理
nginx
的模块直接被编译进nginx
,因此属于静态编译方式。
启动nginx
后,nginx
的模块被自动加载,与Apache
不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。
在解析配置文件时,nginx
的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。
nginx
的进程架构:
启动nginx
时,会启动一个Master
进程,这个进程不处理任何客户端的请求,主要用来产生worker
线程,一个worker
线程用来处理n个request
。
!
下图展示了nginx
模块一次常规的HTTP请求和响应的过程
下图展示了基本的WEB服务请求步骤
5. 部署nginx
//关闭防火墙以及SELinux
[root@kiwi123 nginx-1.22.1]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@kiwi123 nginx-1.22.1]# setenforce 0
[root@kiwi123 nginx-1.22.1]# sed -i 's/^SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
//创建系统用户
[root@kiwi123 ~]# useradd -r -M -s /sbin/nologin nginx
//安装依赖环境
[root@kiwi123 ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make
[root@kiwi123 ~]# yum -y groups mark install 'Development Tools'
//下载安装包
[root@kiwi123 ~]# wget http://nginx.org/download/nginx-1.22.1.tar.gz
//创建日志存放目录
[root@kiwi123 ~]# mkdir -p /var/log/nginx
[root@kiwi123 ~]# chown -R nginx.nginx /var/log/nginx
//开始解压并编译安装
[root@kiwi123 ~]# tar xf nginx-1.22.1.tar.gz && cd nginx-1.22.1
[root@kiwi123 nginx-1.22.1]# ./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
> --with-debug \
> --with-http_ssl_module \
> --with-http_realip_module \
> --with-http_image_filter_module \
> --with-http_gunzip_module \
> --with-http_gzip_static_module \
> --with-http_stub_status_module \
> --http-log-path=/var/log/nginx/access.log \
> --error-log-path=/var/log/nginx/error.log && make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
//配置环境变量
[root@kiwi123 nginx-1.22.1]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@kiwi123 nginx-1.22.1]# source /etc/profile.d/nginx.sh
//配置systemctl文件
[root@kiwi123 nginx-1.22.1]# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx server daemon
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecReload=/usr/local/nginx/sbin/nginx -s reload
[Install]
WantedBy=multi-user.target
[root@kiwi123 nginx-1.22.1]# systemctl daemon-reload
//启动nginx
[root@kiwi123 nginx-1.22.1]# systemctl enable --now nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@kiwi123 nginx-1.22.1]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 511 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
//服务控制方式,使用nginx命令
-t //检查配置文件语法
-v //输出nginx的版本
-c //指定配置文件的路径
-s //发送服务控制信号,可选值有{stop|quit|reopen|reload}
6. nginx的配置文件详解
主配置文件:/usr/local/nginx/conf/nginx.conf
- 默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件
- 可以在启动nginx时通过-c选项来指定要读取的配置文件
[root@kiwi123 ~]# nginx -s stop
[root@kiwi123 ~]# cp /usr/local/nginx/conf/nginx.conf /opt/
[root@kiwi123 ~]# cp /usr/local/nginx/conf/mime.types /opt/
[root@kiwi123 ~]# nginx -c /opt/nginx.conf
nginx常见的配置文件及其作用
配置文件 | 作用 |
---|---|
nginx.conf | nginx的基本配置文件 |
mime.types | MIME类型关联的扩展文件 |
fastcgi.conf | 与fastcgi相关的配置 |
proxy.conf | 与proxy相关的配置 |
sites.conf | 配置nginx提供的网站,包括虚拟主机 |
6.1 nginx.conf配置
nginx.conf的内容分为以下几段:
- main配置段:全局配置段。其中main配置段中可能包含event配置段
- event {}:定义event模型工作特性
- http {}:定义http协议相关的配置
配置指令:要以分号结尾,语法格式如下:
derective value1 [value2 ...];
支持使用变量:
- 内置变量:模块会提供内建变量定义
- 自定义变量:
set var_name value
//例如:
[root@kiwi123 ~]# vim /opt/nginx.conf
user nginx;
error_log /var/log/nginx/error.log;
worker_processes auto;
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name www.kiwi.com;
location / {
root /var/html;
index index.html;
}
}
}
6.2 用于调试、定位问题的配置参数
daemon {on|off}; //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off}; //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别; //配置错误日志
error_log里的位置和级别能有以下可选项:
位置 | 级别 |
---|---|
file stderr syslog:server=address[,parameter=value] memory:size | debug:若要使用debug级别,需要在编译nginx时使用–with-debug选项 info notice warn error crit alert emerg |
[root@kiwi123 ~]# vim /opt/nginx.conf
master_process on;
error_log /var/log/nginx/error.log error; ## 设置为error级别
6.3 正常运行必备的配置参数
user USERNAME [GROUPNAME]; //指定运行worker进程的用户和组
pid /path/to/pid_file; //指定nginx守护进程的pid文件
worker_rlimit_nofile number; //设置所有worker进程最大可以打开的文件数,默认为1024
worker_rlimit_core size; //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可
//指定进程的用户与组
[root@kiwi123 ~]# ps -ef | grep nginx
root 38587 1 0 04:07 ? 00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx 38601 38587 0 04:09 ? 00:00:00 nginx: worker process
root 38603 1635 0 04:09 pts/0 00:00:00 grep --color=auto nginx
[root@kiwi123 ~]# vim /opt/nginx.conf
user root;
[root@kiwi123 ~]# nginx -s reload
[root@kiwi123 ~]# ps -ef | grep nginx
root 38587 1 0 04:07 ? 00:00:00 nginx: master process nginx -c /opt/nginx.conf
root 38595 38587 0 04:09 ? 00:00:00 nginx: worker process
root 38597 1635 0 04:09 pts/0 00:00:00 grep --color=auto nginx
6.4 优化性能的配置参数
worker_processes n; //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...; //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
0000 0001 //第一颗cpu核心
0000 0010 //第二颗cpu核心
0000 0100 //第三颗cpu核心
0000 1000 //第四颗cpu核心
0001 0000 //第五颗cpu核心
0010 0000 //第六颗cpu核心
0100 0000 //第七颗cpu核心
1000 0000 //第八颗cpu核心
timer_resolution interval; //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数,一般保持默认即可
worker_priority number; //指明worker进程的nice值,也就是设置工作进程的优先级,默认为0
//启动多个worker_process进程
[root@kiwi123 ~]# !ps
ps -ef | grep nginx
root 38587 1 0 04:07 ? 00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx 38601 38587 0 04:09 ? 00:00:00 nginx: worker process
root 38607 1635 0 04:13 pts/0 00:00:00 grep --color=auto nginx
[root@kiwi123 ~]# vim /opt/nginx.conf
worker_processes 4;
[root@kiwi123 ~]# nginx -s reload
## 可以看到多了一些进程
[root@kiwi123 ~]# !ps
ps -ef | grep nginx
root 38587 1 0 04:07 ? 00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx 38612 38587 0 04:14 ? 00:00:00 nginx: worker process
nginx 38613 38587 0 04:14 ? 00:00:00 nginx: worker process
nginx 38614 38587 0 04:14 ? 00:00:00 nginx: worker process
nginx 38615 38587 0 04:14 ? 00:00:00 nginx: worker process
root 38617 1635 0 04:14 pts/0 00:00:00 grep --color=auto nginx
[root@kiwi123 ~]#
//将进程绑到cpu中
[root@kiwi123 ~]# vim /opt/nginx.conf
worker_processes 4;
workser_cpu_affinity 0001 0010 0100 1000;
[root@kiwi123 ~]# nginx -s reload
//设置进程优先级
[root@kiwi123 ~]# vim /opt/nginx.conf
worker_priority 1;
[root@kiwi123 ~]# nginx -s reload
6.5 事件相关的配置:event{}段中的配置参数
accept_mutex {off|on}; //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file; //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll]; //指明使用的事件模型,建议让nginx自行选择
worker_connections #; //每个进程能够接受的最大连接数
//例如:
[root@kiwi123 ~]# vim /opt/nginx.conf
events {
accept_mutex on;
worker_connections 1024;
}
6.6 网络连接相关的配置参数
keepalive_timeout number; //长连接的超时时长,默认为65s
keepalive_requests number; //在一个长连接上所能够允许请求的最大资源数
keepalive_disable [msie6|safari|none]; //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off; //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number; //读取http请求报文首部的超时时长
client_body_timeout number; //读取http请求报文body部分的超时时长
send_timeout number; //发送响应报文的超时时长
http {
client_body_timeout 111s;
keepalive_timeout 65;
send_timeout number;
}
6.7 fastcgi的相关配置参数
LNMP:php要启用fpm模型
配置示例如下:
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000; //定义反向代理
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
6.8 常需要进行调整的参数
- worker_processes
- worker_connections
- worker_cpu_affinity
- worker_priority
6.9 nginx作为web服务器时使用的配置:http{}段的配置参数
http{…}:配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块,结构如下:
http {//协议级别
include mime.types;
default_type application/octet-stream;
keepalive_timeout 65;
gzip on;
upstream {//负载均衡配置
...
}
server {//服务器级别,每个server类似于httpd中的一个<VirtualHost>
listen 80;
server_name localhost;
location / {//请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
root html;
index index.html index.htm;
}
}
}
http{}段配置指令:
server {}:定义一个虚拟主机,示例如下:
server {
listen 80;
server_name www.kiwi.com;
root "/vhosts/kiwi";
}
listen:指定监听的地址和端口
listen address[:port];
listen port;
server {
listen 192.168.234.123:80;
server_name www.kiwi123.com;
}
[root@kiwi123 ~]# nginx -s stop
[root@kiwi123 ~]# nginx -c /opt/nginx.conf
[root@kiwi123 ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 511 192.168.234.123:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
server_name NAME [...];
后面可跟多个主机,名称可使用正则表达式或通配符
当有多个server时,匹配顺序如下:
- 先做精确匹配检查
- 左侧通配符匹配检查,如
*.kiwi123.com
- 右侧通配符匹配检查,如
mail.*
- 正则表达式匹配检查,如
~ ^.*\.kiwi123\.com$
- default_server
root path;
设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径
alias path;
用于location配置段,定义路径别名
index file;
默认主页面
index index.php index.html;
location / {
alias /opt/;
index index.html index.htm;
}
error_page code [...] [=code] URI | @name` 根据http响应状态码来指明特用的错误页面,例如 `error_page 404 /404_customed.html
[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404_customed.html
log_format
定义日志格式
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;
//注意:此处可用变量为nginx各模块内建变量
location区段,通过指定模式来与客户端请求的URI相匹配
6.10 访问控制
用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
如:
allow 192.168.234.22/24 192.168.234.33/24;
deny all;
6.11 基于用户认证
auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file"
user_auth_file内容格式为:
username:password
这里的密码为加密后的密码串,建议用htpasswd来创建此文件:
htpasswd -c -m /path/to/.user_auth_file USERNAME
[root@kiwi123 ~]# vim /opt/nginx.conf
location / {
root html;
index index.html index.htm;
}
location /auth_page {
auth_basic "五维猕猴桃";
auth_basic_user_file "/opt/nginx_pass";
index kiwi.html;
}
//下载httpd-tools工具包
[root@kiwi123 opt]# yum install -y httpd-tools
//生成密码文件,注意生成位置
[root@kiwi123 opt]# htpasswd -c -m nginx_pass kiwi
New password:
Re-type new password:
Adding password for user kiwi
[root@kiwi123 opt]# ls
mime.types nginx.conf nginx_ pass
[root@kiwi123 opt]# cat nginx_pass
kiwi:$apr1$rdYVw5ly$82jJbhMslNey.wqPv2/Mr/
//移动kiwi.html文件
[root@kiwi123 html]# ls
50x.html auth_page index.html
[root@kiwi123 html]# ls -l auth_page/
total 4
-rw-r--r-- 1 root root 19 Oct 18 02:27 kiwi.html
//修改默认主页,加上一个超链接
[root@kiwi123 ~]# vim /usr/local/nginx/html/index.html
····················略
<body>
<a href="auth_page/kiwi.html">123</a>
<h1>Welcome to nginx!</h1>
·····················略
//重启服务
[root@kiwi123 ~]# nginx -s stop
[root@kiwi123 ~]# nginx -c /opt/nginx.conf
访问主页无需密码
访问kiwi.html需要密码
6.12 https配置
生成私钥,生成证书签署请求并获得证书,然后在nginx.conf中配置如下内容:
server {
listen 443 ssl;
server_name www.kiwi123.com;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
6.13 开启状态界面
开启status:
location /status {
stub_status {on | off};
allow 192.168.234.123/24;
deny all;
}
[root@kiwi123 ~]# vim /opt/nginx.conf
location /status {
stub_status on ;
}
//重启服务
[root@kiwi123 ~]# curl 192.168.234.123/status
Active connections: 3
server accepts handled requests
3 3 3
Reading: 0 Writing: 1 Waiting: 2
[root@kiwi123 ~]#
访问状态页面的方式:http://server_ip/status
状态页面信息详解:
状态码 | 表示的意义 |
---|---|
Active connections 2 | 当前所有处于打开状态的连接数 |
accepts | 总共处理了多少个连接 |
handled | 成功创建多少握手 |
requests | 总共处理了多少个请求 |
Reading | nginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数 |
Writing | nginx返回给客户端的Header信息数,表示请求已经接收完成, 且正处于处理请求或发送响应的过程中的连接数 |
/server_ip/status` |
状态页面信息详解:
状态码 | 表示的意义 |
---|---|
Active connections 2 | 当前所有处于打开状态的连接数 |
accepts | 总共处理了多少个连接 |
handled | 成功创建多少握手 |
requests | 总共处理了多少个请求 |
Reading | nginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数 |
Writing | nginx返回给客户端的Header信息数,表示请求已经接收完成, 且正处于处理请求或发送响应的过程中的连接数 |
Waiting | 开启keep-alive的情况下,这个值等于active - (reading + writing), 意思就是Nginx已处理完正在等候下一次请求指令的驻留连接 |