一、 概述
Nginx 是开源、高性能、高可靠的 Web服务器 和反向代理服务器,而且支持热部署,几乎可以做到 7 * 24 小时不间断运行,即使运行几个月也不需要重新启动,还能在不间断服务的情况下对软件版本进行热更新。性能是 Nginx 最重要的考量,其占用内存少、并发能力强、能支持高达 5w 个并发连接数,最重要的是, Nginx 是免费的并可以商业化,配置使用也比较简单。
1.1 Nginx 特点
高并发、高性能;
模块化架构使得它的扩展性非常好;
异步非阻塞的事件驱动模型(epoll)这点和 Node.js 相似;
相对于其它服务器来说它可以连续几个月甚至更长而不需要重启服务器使得它具有高可靠性;
热部署、平滑升级;
完全开源,生态繁荣。
1.2 Nginx 作用
http服务器。Nginx可以独立提供http服务。可做网页静态服务器。
虚拟主机。可以实现在一台服务器虚拟出多个虚拟服务器。
反向代理,负载均衡。当网站的访问量达到一定程度后,单台服务器不能满足用户的请求时,需要用多台服务器集群可以使用nginx做反向代理。并且多台服务器可以平均分担负载,不会应为某台服务器负载高宕机而某台服务器闲置的情况。
nginx 中也可以配置安全管理、比如可以使用Nginx搭建API接口网关,对每个接口服务进行拦截。
Nginx的作用
静态服务 | 代理服务 | 安全服务 | 流行架构 |
---|---|---|---|
浏览器缓存 | 协议类型 | 访问控制 | Nginx+PHP(Fastcgi_pass)LNMP |
防资源盗用 | 正向代理 | 访问限制 | Nginx+Java(Proxy_Pass)LNMT |
资源分类 | 反向代理 | 流量限制 | Nginx+Python(uwsgi_pass) |
资源压缩 | 负载均衡 | 拦截攻击 | |
资源缓存 | 代理缓存 | 拦截异常请求 | |
跨域访问 | 动静分离 | 拦截SQL 注入 |
1.3 Nginx工作原理
二、Nginx服务搭建
2.1 Ningx安装
2.1.1 yum安装
yum install -y nginx
##验证安装结果
rpm -q nginx
nginx-1.20.1-7.el7.x86_64
2.1.2 编译安装
[root@nginx1 ~]# tar xf nginx-1.18.0.tar.gz
##安装依赖###
[root@nginx1 ~]# yum install -y pcre-devel
[root@nginx1 ~]# yum install -y zlib-devel
[root@nginx1 ~]# cd nginx-1.18.0/
[root@nginx1 nginx-1.18.0]# ./configure --prefix=/usr/local/nginx1.8 && make && make install
###命令优化
[root@localhost sbin]# export PATH=$PATH:/usr/local/nginx25/sbin #追加到/erc/profile
[root@localhost sbin]# source /etc/profile
##或者
[root@localhost sbin]# ln -s /usr/local/nginx25/sbin/nginx /usr/sbin/
###启停脚本优化
[root@localhost ~]# cat /etc/init.d/nginx
#!/bin/bash
case $1 in
start)
#start
nginx -c /usr/local/nginx25/conf/nginx.conf
;;
stop)
#stop
nginx -s stop
;;
restart)
#stop
#start
nginx -s reopen
;;
reload)
#reload
nginx -s reload
;;
status)
#reload
netstat -anptu | grep nginx
;;
*)
echo "USAGE: $0 start | stop | restart | reload | status"
;;
esac
2.2 目录结构
2.2.1 yum安装
/etc/nginx/ ##配置文件目录
/var/lib/nginx ##临时数据文件目录
/var/log/nginx/ ##日志文件目录
/usr/share/nginx/html/ ##访问页面根目录
/etc/nginx/conf.d ##自定义配置文件目录
/etc/nginx/default.d ##默认配置文件目录
2.2.2 编译安装
/usr/local/nginx1.8/conf ##配置文件目录
/usr/local/nginx1.8/conf/conf.d ##自定义配置文件目录
/usr/local/nginx1.8/conf/default.d ##默认配置文件目录
/usr/local/nginx1.8/html ##访问页面根目录
/usr/local/nginx1.8/logs ##日志文件目录
/usr/local/nginx1.8/sbin ##命令存放目录
2.3 核心配置文件
[root@t1000 nginx-1.25.3]# cd /usr/local/nginx1.25/
[root@t1000 nginx1.25]# ls
conf html logs sbin
[root@t1000 nginx1.25]# cd conf
[root@t1000 conf]# ls
fastcgi.conf koi-utf nginx.conf uwsgi_params
fastcgi.conf.default koi-win nginx.conf.default uwsgi_params.default
fastcgi_params mime.types scgi_params win-utf
fastcgi_params.default mime.types.default scgi_params.default
配置文件作用表
配置文件名称 | 配置文件作用 |
---|---|
fastcgi.conf | 此文件包含了FastCGI相关的配置,用于与FastCGI进程通信 |
fastcgi.conf.default | 此文件是fastcgi.conf的备份副本 |
fastcgi_params | 此文件包含了用于FastCGI的参数配置,包括fastcgi的传输协议、请求超时时间等 |
fastcgi_params.default | 此文件是fastcgi_params的备份副本 |
koi-utf | 此文件包含了UTF-8编码与KOI8-R编码之间的字符转换规则,用于处理中文文件名等问题 |
koi-win | 此文件包含了Windows系统的字符转换规则,用于处理Windows系统的文件名问题 |
mime.types | 此文件包含了Nginx支持的MIME类型配置,用于设置相应的Content-Type头 |
mime.types.default | 此文件是mime.types的备份副本 |
nginx.conf | Nginx的主要配置文件,其中包含了所有全局配置和访问控制规则,作为Nginx服务器的入口文件 |
nginx.conf.default | 此文件是nginx.conf的备份副本 |
scgi_params | 此文件包含了用于SCGI协议的参数配置 |
scgi_params.default | 此文件是scgi_params的备份副本 |
uwsgi_params | 此文件包含了用于uWSGI协议的参数配置 |
uwsgi_params.default | 此文件是uwsgi_params的备份副本 |
win-utf | 此文件包含了Windows系统的字符转换规则,用于处理Windows系统的文件名问题 |
编译安装 Nginx 编译配置选项
[root@t1000 ~]# cd nginx-1.25.3/
[root@t1000 nginx-1.25.3]# ls
auto CHANGES.ru configure html Makefile objs src
CHANGES conf contrib LICENSE man README
[root@t1000 nginx-1.25.3]# ./configure --help
基本选项
--help 打印帮助信息
--prefix=PATH 设置安装路径前缀
--sbin-path=PATH 设置 Nginx 可执行文件路径
--modules-path=PATH 设置模块存放路径
--conf-path=PATH 设置 nginx.conf 配置文件路径
--error-log-path=PATH 设置错误日志路径
--pid-path=PATH 设置 nginx.pid 文件路径
--lock-path=PATH 设置 nginx.lock 文件路径
进程权限
--user=USER 设置 Worker 进程非特权用户
--group=GROUP 设置 Worker 进程非特权用户组
构建配置
--build=NAME 设置构建名称
--builddir=DIR 设置构建目录
事件模块
--with-select_module 启用 select 事件模块
--without-select_module 禁用 select 事件模块
--with-poll_module 启用 poll 事件模块
--without-poll_module 禁用 poll 事件模块
核心功能
--with-threads 启用线程池支持
--with-file-aio 启用文件异步 I/O 支持
--without-quic_bpf_module 禁用 ngx_quic_bpf_module
HTTP 模块 (启用)
--with-http_ssl_module 启用 HTTPS 支持 (ngx_http_ssl_module)
--with-http_v2_module 启用 HTTP/2 支持
--with-http_v3_module 启用 HTTP/3 支持
--with-http_realip_module 启用真实客户端 IP 解析模块
--with-http_addition_module 启用响应内容追加模块
--with-http_xslt_module 启用 XSLT 样式表转换模块
--with-http_xslt_module=dynamic 启用动态加载的 XSLT 模块
--with-http_image_filter_module 启用图像过滤模块
--with-http_image_filter_module=dynamic 动态加载图像过滤模块
--with-http_geoip_module 启用基于 IP 的地理定位模块
--with-http_geoip_module=dynamic 动态加载地理定位模块
(其他启用模块类似,翻译略)
HTTP 模块 (禁用)
--without-http_charset_module 禁用字符集转换模块
--without-http_gzip_module 禁用 GZIP 压缩模块
--without-http_ssi_module 禁用 SSI 服务端包含模块
(其他禁用模块类似,翻译略)
Perl 模块
--with-http_perl_module 启用 Perl 脚本支持模块
--with-http_perl_module=dynamic 启用动态加载的 Perl 模块
--with-perl_modules_path=PATH 设置 Perl 模块路径
--with-perl=PATH 指定 Perl 可执行文件路径
HTTP 路径设置
--http-log-path=PATH 设置 HTTP 访问日志路径
--http-client-body-temp-path=PATH 设置客户端请求体临时文件存储路径
--http-proxy-temp-path=PATH 设置 HTTP 代理临时文件存储路径
(其他临时路径类似,翻译略)
HTTP 功能开关
--without-http 禁用 HTTP 服务器功能
--without-http-cache 禁用 HTTP 缓存功能
邮件代理模块
--with-mail 启用邮件代理模块 (POP3/IMAP4/SMTP)
--with-mail=dynamic 启用动态加载的邮件代理模块
--with-mail_ssl_module 启用邮件 SSL/TLS 支持
--without-mail_pop3_module 禁用 POP3 协议支持
--without-mail_imap_module 禁用 IMAP4 协议支持
--without-mail_smtp_module 禁用 SMTP 协议支持
TCP/UDP 代理模块
--with-stream 启用 TCP/UDP 代理模块
--with-stream=dynamic 启用动态加载的 TCP/UDP 代理模块
--with-stream_ssl_module 启用流式 SSL/TLS 支持
--with-stream_realip_module 启用流式真实 IP 解析模块
(其他启用模块类似,翻译略)
--without-stream_limit_conn_module 禁用流式连接限制模块
(其他禁用模块类似,翻译略)
其他模块
--with-google_perftools_module 启用 Google Performance Tools 模块
--with-cpp_test_module 启用 C++ 测试模块
外部模块
--add-module=PATH 添加外部静态模块
--add-dynamic-module=PATH 添加外部动态模块
兼容性
--with-compat 启用动态模块兼容模式
编译工具链
--with-cc=PATH 指定 C 编译器路径
--with-cpp=PATH 指定 C 预处理器路径
--with-cc-opt=OPTIONS 附加 C 编译器选项
--with-ld-opt=OPTIONS 附加链接器选项
--with-cpu-opt=CPU 指定 CPU 优化架构 (可选: pentium, pentiumpro, athlon, sparc64 等)
依赖库配置
--without-pcre 禁用 PCRE 库
--with-pcre 强制使用 PCRE 库
--with-pcre=DIR 指定 PCRE 库源码路径
--with-pcre-opt=OPTIONS 附加 PCRE 编译选项
--with-pcre-jit 启用 PCRE JIT 编译优化
--without-pcre2 禁用 PCRE2 库
--with-zlib=DIR 指定 zlib 库源码路径
--with-zlib-opt=OPTIONS 附加 zlib 编译选项
--with-zlib-asm=CPU 使用 zlib 指定 CPU 的汇编优化 (pentium/pentiumpro)
--with-libatomic 强制使用 libatomic_ops 库
--with-libatomic=DIR 指定 libatomic_ops 库源码路径
--with-openssl=DIR 指定 OpenSSL 库源码路径
--with-openssl-opt=OPTIONS 附加 OpenSSL 编译选项
调试
--with-debug 启用调试日志
2.3.1 nginx.conf配置文件详解
##全局配置,对全局生效##
user nobody nobody; # 指定运行 Nginx 进程的用户为 nobody,组为nobody
pid /var/run/nginx.pid # master主进程的的pid存放在nginx.pid的文件
worker_processes 1; # 指定 Nginx 启动的 worker 子进程数量。
#worker_processes auto; # 与当前cpu物理核心数一致
worker_rlimit_nofile 20480; # 指定 worker 子进程可以打开的最大文件句柄数。
worker_rlimit_core 50M; # 指定 worker 子进程异常终止后的 core 文件,用于记录分析问题。
working_directory /opt/nginx/tmp; # 存放目录
worker_priority -10; # 指定 worker 子进程的 nice 值,以调整运行 Nginx 的优先级,通常设定为负值,以优先调用 Nginx。
#Linux 默认进程的优先级值是120,值越小越优先;nice 定范围为 -20 到 +19 。
#应用的默认优先级值是120加上 nice 值等于它最终的值,这个值越小,优先级越高。
worker_shutdown_timeout 5s; #指定 worker 子进程优雅退出时的超时时间。
timer_resolution 100ms; #worker ,调整时间间隔越大,系统调用越少,有利于性能提升;反之,系统调用越多,性能下降。
daemon on; # 指定 Nginx 的运行方式,前台还是后台,前台用于调试,后台用于生产。默认是on,后台运行模式。
error_log logs/error.log; # 错误日志文件路径
##events:配置影响 Nginx 服务器与用户的网络连接;##
events {
use epoll; # 使用epoll的I/O模型(如果你不知道Nginx该使用哪种轮询方法,会自动选择一个最适合你操作系统的)
worker_connections 1024; # 允许的最大并发连接数
accept_mutex on; # 是否打开负载均衡互斥锁,默认是off关闭的,这里推荐打开
}
##http:配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置;##
http {
include mime.types; # 包含 MIME 类型的定义,文件扩展名与类型映射表
default_type application/octet-stream; # 默认文件类型
default_type application/octet-stream; # 默认的 MIME 类型
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; # 访问日志文件及使用的日志格式
sendfile on; # 启用零拷贝传输,高效传输模式
tcp_nopush on; # 启用 TCP nopush 选项,减少网络报文段的数量
keepalive_timeout 0; # 禁用持久连接的超时时间
keepalive_timeout 65; # 保持存活连接的超时时间
gzip on; # 开启 Gzip 压缩
include /etc/nginx/conf.d/*.conf; # 加载自定义配置项
##upstream:配置后端服务器具体地址,负载均衡配置不可或缺的部分。##
upstream back_end_server{
server 192.168.100.33:8081 #定义后端web服务器节点
}
##server:配置虚拟主机的相关参数,一个 http 块中可以有多个 server 块;每个nginx相当于一个虚拟服务器的地位。##
server {
listen 80; # 监听端口 80
server_name localhost; # 服务器名为 localhost
charset koi8-r; # 字符集设置为 koi8-r
access_log logs/host.access.log main; # 主机访问日志文件及使用的日志格式
##location:用于配置匹配的 uri ;##
location / {
root html; # 指定静态资源目录位置,它可以写在 http 、 server 、 location 等配置中。
index index.html index.htm; # 默认的索引文件
deny 172.168.22.11; # 禁止访问的ip地址,可以为all
allow 172.168.33.44;# 允许访问的ip地址,可以为all
}
location /image {
alias /opt/nginx/static/image/;#它也是指定静态资源目录位置,使用alias末尾一定要添加 / ,只能写在 location 中。
}
#当用户访问 www.jx.com/image/1.png 时,实际在服务器找的路径是 /opt/nginx/static/image/1.png
error_page 404 /404.html; # 设置 404 错误页面的位置为 /404.html
error_page 500 502 503 504 /50x.html; # 将服务器错误页面重定向到 /50x.html
location = /50x.html {
root html;
}
location ~ \.php$ {
proxy_pass http://127.0.0.1; # 将 PHP 脚本代理到监听在 127.0.0.1:80 上的 Apache 服务器
}
location ~ \.php$ {
root html; # PHP 脚本位置
fastcgi_pass 127.0.0.1:9000; # 向 FastCGI 服务器传递 PHP 脚本
fastcgi_index index.php; # 指定 FastCGI 服务器默认的脚本文件名
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # FastCGI 参数配置
include fastcgi_params; # 包含 FastCGI 相关的参数配置
}
location ~ /\.ht {
deny all; # 阻止访问 .htaccess 文件
}
}
server {
listen 8000; # 监听端口 8000
listen somename:8080; # 监听 somename:8080
server_name somename alias another.alias; # 服务器名设置
location / {
root html; # 根目录位置为 html 文件夹
index index.html index.htm; # 默认的索引文件
}
}
server {
listen 443 ssl; # 启动在 443 端口,并开启 SSL
server_name localhost; # 服务器名为 localhost
ssl_certificate cert.pem; # SSL 证书文件
ssl_certificate_key cert.key; # SSL 证书的私钥文件
ssl_session_cache shared:SSL:1m; # 配置 SSL 会话缓存
ssl_session_timeout 5m; # SSL 会话缓存的超时时间设置为 5 分钟
ssl_ciphers HIGH:!aNULL:!MD5; # 配置 SSL 加密算法
ssl_prefer_server_ciphers on; # 优先使用服务器端的加密套件
location / {
root html; # 根目录位置为 html 文件夹
index index.html index.htm; # 默认的索引文件
}
}
}
2.3.2 配置文件层级结构图
2.4 核心命令
命令 | 作用 |
---|---|
systemctl enable nginx | 开机自动启动 |
systemctl disable nginx | 关闭开机自动启动 |
systemctl start nginx | 启动Nginx |
systemctl stop nginx | 停止Nginx |
systemctl restart nginx | 重启Nginx |
systemctl reload nginx | 重新加载Nginx |
systemctl status nginx | 查看 Nginx 运行状态 |
ps -elf | grep [n]ginx | 查看Nginx进程,但是不会显示grep本身的进程 |
kill -9 pid | 根据上面查看到的Nginx进程号,杀死Nginx进程,-9 表示强制结束进程 |
nginx -s reload | 向主进程发送信号,重新加载配置文件,热重启 |
nginx -s reopen | 重启 Nginx |
nginx -s stop | 快速关闭 |
nginx -s quit | 等待工作进程处理完成后关闭 |
nginx -T | 查看当前 Nginx 最终的配置 |
nginx -t | 检查配置是否有问题 |
nginx -c configfilePath | 指定配置文件启动nginx |
2.5 Nginx信号
信号名 | 含义 |
---|---|
stop | 直接停止 |
quit | 优雅的退出:有人在访问不会结束进程 |
reopen | 分割日志 |
reload | 重新加载配置文件 |
term | 快速停止nginx进程,可能会中断现有连接,与stop信号类似。 |
usr1 | 重新打开日志文件,用于日志切割或日志重定向,与reopen信号类似。 |
usr2 | 平滑地升级nginx可执行文件。 |
hup | 重新加载配置文件,优雅地应用新配置,与reload信号类似。 |
winch | 当nginx以master/worker工作模式运行时,重新生成worker进程以适应新的配置。 |
usr3 | 向worker进程发送自定义信号。 |
三、配置案例
3.1 单站点配置
安装完毕启动nginx服务即可!!
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
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;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
nginx.conf.default配置文件
user nobody;
worker_processes 1;
#error_log /var/log/nginx/error.log;
#error_log /var/log/nginx/error.log notice;
error_log /var/log/nginx/error.log info;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
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;
sendfile on;
tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
server {
listen 80;
server_name localhost;
charset utf8;
access_log /var/log/nginx/access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#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;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.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;
# }
#}
}
3.2 虚拟机主机头配置
3.2.1 基于IP地址
user nobody;
worker_processes 1;
#error_log /var/log/nginx/error.log;
#error_log /var/log/nginx/error.log notice;
error_log /var/log/nginx/error.log info;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
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;
sendfile on;
tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
server {
listen 192.168.115.111:80; #更改同端口下的不同IP
server_name _;
charset utf8;
access_log /var/log/nginx/access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
server {
listen 192.168.115.114:80; #更改同端口下的不同IP,可以同块网卡设置额外的子接口
server_name _;
location / {
root /var/www/html;
index index.html index.htm;
}
}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.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;
# }
#}
}
3.2.2 基于域名
user nobody;
worker_processes 1;
#error_log /var/log/nginx/error.log;
#error_log /var/log/nginx/error.log notice;
error_log /var/log/nginx/error.log info;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
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;
sendfile on;
tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
server {
listen 192.168.115.111:80;
server_name www1.jx.com; #设置域名,通过域名访问,不过访问端需要设置 /etc/hosts
charset utf8;
access_log /var/log/nginx/access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
server {
listen 192.168.115.114:80;
server_name www2.jx.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.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;
# }
#}
}
3.2.3 基于端口号
user nobody;
worker_processes 1;
#error_log /var/log/nginx/error.log;
#error_log /var/log/nginx/error.log notice;
error_log /var/log/nginx/error.log info;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
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;
sendfile on;
tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
server {
listen 192.168.115.111:80; #增添端口 访问同一IP的不同端口
server_name www1.jx.com;
charset utf8;
access_log /var/log/nginx/access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
server {
listen 192.168.115.114:81;
server_name www2.jx.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.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;
# }
#}
}
server_name 指定虚拟主机域名
域名匹配的四种写法:
精确匹配:server_name www.nginx.com ;
左侧通配:server_name *.nginx.com ;
右侧通配:server_name www.nginx.* ;
正则匹配:server_name ~^www.nginx.*$ ;
FQDN(完全限定域名):主机名.二级域.顶级域.
匹配优先级:精确匹配 > 左侧通配符匹配 > 右侧通配符匹配 > 正则表达式匹配。
server_name 配置实例:
#配置192.168.115.111为nginx服务器
vim /etc/nginx/nginx.conf
# 在http字段中的sever字段配置 # 左匹配
server {
listen 80;
server_name *.nginx-test.com;
root /usr/share/nginx/html/nginx-test/left-match/;
location / {
index index.html;
}
}
# 正则匹配
server {
listen 80;
server_name ~^.*\.nginx-test\..*$;
root /usr/share/nginx/html/nginx-test/reg-match/;
location / {
index index.html;
}
}
# 右匹配
server {
listen 80;
server_name www.nginx-test.*;
root /usr/share/nginx/html/nginx-test/right-match/;
location / {
index index.html;
}
}
# 完全匹配
server {
listen 80;
server_name www.nginx-test.com;
root /usr/share/nginx/html/nginx-test/all-match/;
location / {
index index.html;
}
}
#配置客户端 DNS解析。
vim /etc/hosts
192.168.115.111 www.nginx-test.com
192.168.115.111 mail.nginx-test.com
192.168.115.111 www.nginx-test.org
192.168.115.111 doc.nginx-test.com
192.168.115.111 www.nginx-test.cn
192.168.115.111 fe.nginx-test.club
#访问分析 #当访问 www.jx.com 时,都可以被匹配上,因此选择优先级最高的“完全匹配”; #当访问 mail.nginx-test.com 时,会进行“左匹配”; #当访问 www.nginx-test.org 时,会进行“右匹配”; #当访问 doc.nginx-test.com 时,会进行“左匹配”; #当访问 www.nginx-test.cn 时,会进行“右匹配”; #当访问 fe.nginx-test.club 时,会进行“正则匹配”。
四、HTTPS访问配置[自签名]
4.1 SSL简介
SSL (Secure Sockets Layer)安全套接层。是由Netscape(网景)公司于1990年开发,用于保障Word Wide Web(WWW)通讯的安全。主要任务是提供私密性,信息完整性和身份认证。1994年改版为SSLv2,1995年改版为SSLv3.
TLS(Transport Layer Security)安全传输层协议,)用于在两个通信应用程序之间提供保密性和数据完整性。该标准协议是由IETF于1999年颁布,整体来说TLS非常类似SSLv3,只是对SSLv3做了些增加和修改。
4.2 SSL协议介绍
SSL是一个不依赖于平台和应用程序的协议,位于TCP/IP协议与各种应用层协议之间,为数据通信提高安全支持。
4.3 传输过程
首先发送数字证书,获取到可信的public key。
通过public key发送对称秘钥,接收方用私钥解密。
通信双方使用仅仅对方可知的对称秘钥进行加密传输。
4.5 OpenSSL介绍
OpenSSL是一个实现安全套接字层的加密工具包,openssl程序是一个命令行工具,用于使用OpenSSL加密库的加密函数。它可以用于:
创建和管理私钥、公钥和参数
公钥密码操作
创建X.509证书、CSR和CRT
消息摘要的计算
密码加密和解密
SSL/TLS客户端和服务器测试
处理S/MIME签名或加密邮件
时间戳请求、生成和验证
4.6 HTTPS 工作流程
客户端(浏览器)访问 百度一下,你就知道 百度网站;
百度服务器返回 HTTPS 使用的 CA 证书;
浏览器验证 CA 证书是否为合法证书;
验证通过,证书合法,生成一串随机数并使用公钥(证书中提供的)进行加密;
发送公钥加密后的随机数给百度服务器;
百度服务器拿到密文,通过私钥进行解密,获取到随机数(公钥加密,私钥解密,反之也可以);
百度服务器把要发送给浏览器的内容,使用随机数进行加密后传输给浏览器;(对称加密)
此时浏览器可以使用随机数进行解密,获取到服务器的真实传输内容。
案例:
[root@nginx1 ~]#openssl genrsa -out rsa1024.key 1024
[root@nginx1 ~]#openssl req -new -key rsa1024.key -out rsa1024.csr
[root@nginx1 ~]#openssl x509 -req -days 365 -in rsa1024.csr -signkey rsa1024.key -out rsa1024.crt
4.7 自签名证书
[root@nginx1 ~]# mkdir /usr/share/nginx/pki/private -p
#生成私钥文件(包含公钥和私钥)
[root@nginx1 ~]# cd /usr/share/nginx/pki/private
[root@nginx1 private]# openssl genrsa -out nginx.key
#查看私钥文件:
[root@nginx1 private]# openssl rsa -in nginx.key -text
#生成证书请求文件
[root@nginx1 ~]# cd /usr/share/nginx/
[root@nginx1 nginx]# openssl req -new -key ./private/nginx.key -out nginx.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:BJ
Locality Name (eg, city) [Default City]:BJ
Organization Name (eg, company) [Default Company Ltd]:jx
Organizational Unit Name (eg, section) []:2310
Common Name (eg, your name or your server's hostname) []:www.jx.com
Email Address []:2310@jx.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:jx
#生成证书
[root@nginx1 ~]# cd /etc/pki/nginx
[root@nginx1 nginx]# openssl x509 -req -days 3650 -in nginx.csr -signkey ./private/nginx.key -out nginx.crt
#查看证书:
[root@nginx1 nginx]# openssl x509 -req -days 3650 -in nginx.csr -signkey ./private/nginx.key -text
4.8 nginx配置SSL
server {
listen 443 ssl;
server_name www.jx.com;
ssl_certificate ../pki/nginx/nginx.crt;
ssl_certificate_key ../pki/nginx/private/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;
}
}
4.9 测试
五、 location配置
5.1 作用
配置路径
location [ = | ~ | ~* | ^~ ] uri {
...
}
##在浏览器中输入的:http://www.jx.com/s?id=1&test=123,称作URL,即:统一资源定位符 ##在WEB服务器中,对资源进行标识,URI,即统一资源标识符
写在server字段中。
5.2 匹配规则
= 精确匹配;
~ 正则匹配,区分大小写;
~* 正则匹配,不区分大小写;
^~ 匹配到即停止搜索;
5.3 匹配优先级
= > ^~ > ~ > ~* > 不带任何字符 “/”。
5.4 配置案例
server {
listen 80;
server_name www.jx.com;
# 只有当访问 www.jx.com/info.html 时才会匹配到/usr/share/nginx/html/info.html
location = /info.html { # 必须是匹配文件
root /usr/share/nginx/html;
}
# 当访问 www.jx.com/1.jpg 等路径时会去 /usr/share/nginx/images/1.jpg 找对应的资源
location ~ \.(jpeg|jpg|png|svg)$ {
root /usr/share/nginx/html/images;
}
# 当访问 www.jx.com/bbs/ 时会匹配上 /usr/share/nginx/html/bbs/index.html
location ^~ /bbs/ {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
1、location 中的反斜线,代表后面的名字是一个文件夹名
location /test {
...
}
##以上写法会优先查找目录,若目录不存在则查找同名文件
location /test/ {
...
}
2、return
停止处理请求,直接返回响应码或重定向到其他 URL ;执行 return 指令后, location 中后续指令将不会被执行。
return code [text]; return code URL; return URL; 例如:
location / {
return 404; # 直接返回状态码
}
location / {
return 404 "pages not found"; # 返回状态码 + 一段文本
}
location / {
return 302 http://192.168.88.130/bbs ; # 返回状态码 + 重定向地址
}
location / {
return https://www.baidu.com ; # 返回重定向地址
}
会重定向到百度
六、rewrite配置
根据指定正则表达式匹配规则,重写 URL 。应用场景: 新老域名的更替!!!
6.1 语法
rewrite 正则表达式 要替换的内容 [flag];
6.2 可写入字段
server、location、if
示例:
rewirte /images/(.*\.jpg)$ /pic/$1; # $1是前面括号(.*\.jpg)的反向引用
flag 可选值的含义:
last: 重写后的 URL 发起新请求,再次进入 server 段,重试 location 的中的匹配;
break :直接使用重写后的 URL ,不再匹配其它 location 中语句;
redirect :返回 302 临时重定向;
permanent :返回 301 永久重定向。
6.3 配置案例
server{
listen 80;
server_name www.jx.com; # 要在本地hosts文件进行配置
root /usr/share/nginx/html;
location /search {
rewrite ^/(.*) https://www.baidu.com redirect;
}
location /images {
rewrite /images/(.*) /pics/$1;
}
location /pics {
rewrite /pics/(.*) /photos/$1;
}
location /photos {
}
}
###生产环境不能使用.*,表示匹配任意!!! #解析: #当访问 www.jx.com/search 时,会自动帮我们重定向到 https://www.baidu.com; #当访问 www.jx.com/images/1.jpg 时,第一步重写 URL 为 www.jx.com/pics/1.jpg ,找到 pics 的 location ,继续重写 URL 为 www.jx.com/photos/1.jpg ,找到 /photos 的 location 后,去 html/photos 目录下寻找 1.jpg 静态资源。
6.4 if 指令
语法:if (condition) {...}
可写字段:server、location
示例:
location / {
if ($http_user_agent ~ Chrome) {
rewrite /(.*) /Chrome/$1 break;
}
if ($http_user_agent ~ Firefox) {
rewrite /(.*) /Firefox/$1 break;
}
}
##测试192.168.115.111/index.html
set $var value; #设置变量
condition 判断条件:
$variable 仅为变量时,值为空或以0开头字符串都会被当做 false 处理;
= 或 != 相等或不等;
~ 正则匹配;
! ~ 非正则匹配;
~* 正则匹配,不区分大小写;
-f 或 ! -f 检测文件存在或不存在;
-d 或 ! -d 检测目录存在或不存在;
-e 或 ! -e 检测文件、目录、符号链接等存在或不存在;
-x 或 ! -x 检测文件可以执行或不可执行;
配置实例
server {
listen 8080;
server_name www.jx.com;
root /usr/share/nginx/html;
location / {
if ( $uri = "/images/" ){
rewrite (.*) /pics/ break;
}
}
}
#当访问 www.jx.com/images/ 时,会进入 if 判断里面执行 rewrite 命令。
6.5 autoindex
用户请求以 / 结尾时,列出目录结构,可以用于快速搭建静态资源下载网站。
注意!不要在有混合业务的站点开启此功能!容易被攻击!
autoindex.conf 配置信息:
server {
listen 80;
server_name www.jx.com;
location /download/ {
root /usr/share/nginx/html;
autoindex on; # 打开 autoindex,,可选参数有 on | off
autoindex_exact_size on; # 修改为off,以KB、MB、GB显示文件大小,默认为on,以bytes显示出⽂件的确切⼤⼩
autoindex_format html; # 以html的方式进行格式化,可选参数有 html | json | xml
autoindex_localtime off; # 显示的⽂件时间为⽂件的服务器时间。默认为off,显示的⽂件时间为GMT时间
}
}
#当访问 www.jx.com/download/ 时,会把服务器 /usr/share/nginx/html/download/ 路径下的文件展示出来.
6.6 nginx配置中的常用变量
变量名 | 含义 |
---|---|
remote_add | 客户端IP地址 |
remote_port | 客户端端口 |
server_addr | 服务端IP地址 |
Server_port | 服务端端口 |
server_protocol | 服务端协议 |
binary_remote_addr | 二进制格式的客户端IP地址 |
connection | TCP连接的序号,递增 |
connection_request | TCP连接当前的请求数量 |
uri | 请求的URL,不包含参数 |
request ur | 请求的URL,包含参数 |
scheme | 协议名,http或https |
request metho | 请求方法 |
request_length | 全部请求的长度,包含请求行、请求头、请求体 |
args | 全部参数字符串 |
arg_参数名 | 获取特定参数值 |
is_args | URL中是否有参数,有的话返回?,否则返回空 |
query_string | 与args相同 |
host | 请求信息中的Host,如果请求中没有Host行,则在请求头中找,最后 使用nginx中设置的server_name。 |
http_user_agent | 用户访问方式 |
http_referer | 从哪些链接过来的请求 |
http_via | 每经过一层代理服务器,都会添加相应的信息 |
http_cookie | 获取用户cookie |
request time | 处理请求已消耗的时间 |
https | 是否开启了https,是则返回on,否则返回空 |
request_filename | 磁盘文件系统待访问文件的完整路径 |
document_root | 由URI和root/alias规则生成的文件夹路径 |
limit_rate | 返回响应时的速度上限值 |
配置案例
server{
listen 8081;
server_name www.jx.com;
root /usr/share/nginx/html;
location / {
return 200 "
remote_addr: $remote_addr
remote_port: $remote_port
server_addr: $server_addr
server_port: $server_port
server_protocol: $server_protocol
binary_remote_addr: $binary_remote_addr
connection: $connection
uri: $uri
request_uri: $request_uri
scheme: $scheme
request_method: $request_method
request_length: $request_length
args: $args
arg_pid: $arg_pid
is_args: $is_args
query_string: $query_string
host: $host
http_user_agent: $http_user_agent
http_referer: $http_referer
http_via: $http_via
request_time: $request_time
https: $https
request_filename: $request_filename
document_root: $document_root
";
}
}
当我们访问 http://www.jx.com/时,由于 Nginx 中写了 return 方法,因此浏览器会默认为我们下载一个文件,下面展示的就是下载的文件内容:
remote_addr: 192.168.115.112
remote_port: 56838
server_addr: 192.168.115.111
server_port: 8081
server_protocol: HTTP/1.1
binary_remote_addr: 茉
connection: 126
uri: /test/
request_uri: /test/?pid=121414&cid=sadasd
scheme: http
request_method: GET
request_length: 518
args: pid=121414&cid=sadasd
arg_pid: 121414
is_args: ?
query_string: pid=121414&cid=sadasd
host: var.lion-test.club
http_user_agent: Mozilla/5.0 (Windows NT 7.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0
http_referer:
http_via:
request_time: 0.000
https:
request_filename: /usr/share/nginx/html/test/
document_root: /usr/share/nginx/html
七、配置Nignx状态统计
1、下载vts模块
https://github.com/vozlt/nginx-module-vts
2、编译nginx
tar xf nginx-module-vts-master.zip
cd nginx-1.22.1/
./configure --prefix=/usr/local/nginx/ --add-module=/root/nginx-module-vts-master && make && make install
3、配置状态统计页面
user nginx;
worker_processes 1;
error_log logs/error.log info;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
sendfile on;
keepalive_timeout 65;
gzip on;
##添加如下配置###
vhost_traffic_status_zone;
server {
listen 80;
server_name localhost;
charset utf-8;
access_log logs/$server_addr.access.log main;
location / {
root html;
index index.html index.htm;
}
##添加如下配置####
location /status {
vhost_traffic_status_display;
vhost_traffic_status_display_format html;
}
error_page 404 /404.html;
location = /404.html {
root html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}