Nginx介绍
Nginx是lgor Sysoev为俄罗斯访问量第二的rambler.ru站点设计开发的。从2004年发布至今,凭借开源的力量,已经接近成熟与完善。
Nginx功能丰富,可作为HTTP服务器,也可作为反向代理服务器,邮件服务器。支持FastCGI、SSL、Virtual Host、URL Rewrite、Gzip等功能。并且支持很多第三方的模块扩展。
Nginx的稳定性、功能集、示例配置文件和低系统资源的消耗让他后来居上,在全球活跃的网站中有12.18%的使用比率,大约为2220万个网站。
Nginx常用功能
Http代理,反向代理
作为web服务器最常用的功能之一,尤其是反向代理。

Nginx在做反向代理时,提供性能稳定,并且能够提供配置灵活的转发功能。Nginx可以根据不同的正则匹配,采取不同的转发策略,比如图片文件结尾的走文件服务器,动态页面走web服务器,只要你正则写的没问题,又有相对应的服务器解决方案,你就可以随心所欲的玩。并且Nginx对返回结果进行错误页跳转,异常判断等。如果被分发的服务器存在异常,他可以将请求重新转发给另外一台服务器,然后自动去除异常服务器。
负载均衡
Nginx提供的负载均衡策略有2种:内置策略和扩展策略。

Ip hash算法,对客户端请求的ip进行hash操作,然后根据hash结果将同一个客户端ip的请求分发给同一台服务器进行处理,可以解决session不共享的问题。

web缓存
Nginx可以对不同的文件做不同的缓存处理,配置灵活,并且支持FastCGI_Cache,主要用于对FastCGI的动态程序进行缓存。配合着第三方的ngx_cache_purge,对制定的URL缓存内容可以的进行增删管理。
Nginx相关地址
源码:https://trac.nginx.org/nginx/browser
官网:http://www.nginx.org/
Nginx配置文件结构
在 nginx.conf 的注释符号为: #
默认的 nginx 配置文件 nginx.conf 内容如下:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#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"';
#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 koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root 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;
# }
#}
}
nginx 文件结构
... #全局块
events { #events块
...
}
http #http块
{
... #http全局块
server #server块
{
... #server全局块
location [PATTERN] #location块
{
...
}
location [PATTERN]
{
...
}
}
server
{
...
}
... #http全局块
}
1、全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。
2、events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。
3、http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。
4、server块:配置虚拟主机的相关参数,一个http中可以有多个server。
5、location块:配置请求的路由,以及各种页面的处理情况。
1、几个常见配置项:
1.$remote_addr 与 $http_x_forwarded_for 用以记录客户端的ip地址;
2.$remote_user :用来记录客户端用户名称;
3.$time_local : 用来记录访问时间与时区;
4.$request : 用来记录请求的url与http协议;
5.$status : 用来记录请求状态;成功是200;
6.$body_bytes_s ent :记录发送给客户端文件主体内容大小;
7.$http_referer :用来记录从那个页面链接访问过来的;
8.$http_user_agent :记录客户端浏览器的相关信息;
2、惊群现象:一个网路连接到来,多个睡眠的进程被同时叫醒,但只有一个进程能获得链接,这样会影响系统性能。
3、每个指令必须有分号结束。
举例:
#user administrator administrators; #配置用户或者组,默认为nobody nobody。
#worker_processes 2; #允许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid; #指定nginx进程运行文件存放地址
error_log log/error.log debug; #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
accept_mutex on; #设置网路连接序列化,防止惊群现象发生,默认为on
multi_accept on; #设置一个进程是否同时接受多个网络连接,默认为off
#use epoll; #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
worker_connections 1024; #最大连接数,默认为512
}
http {
include mime.types; #文件扩展名与文件类型映射表
default_type application/octet-stream; #默认文件类型,默认为text/plain
#access_log off; #取消服务日志
log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
access_log log/access.log myFormat; #combined为日志格式的默认值
sendfile on; #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
sendfile_max_chunk 100k; #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
keepalive_timeout 65; #连接超时时间,默认为75s,可以在http,server,location块。
upstream mysvr {
server 127.0.0.1:7878;
server 192.168.10.121:3333 backup; #热备
}
error_page 404 https://www.baidu.com; #错误页
server {
keepalive_requests 120; #单连接请求上限次数。
listen 4545; #监听端口
server_name 127.0.0.1; #监听地址
location ~*^.+$ { #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
#root path; #根目录
#index vv.txt; #设置默认页
proxy_pass http://mysvr; #请求转向mysvr 定义的服务器列表
deny 127.0.0.1; #拒绝的ip
allow 172.18.5.54; #允许的ip
}
}
}
实验项目
编译安装 Nginx
下载安装包nginx-1.24.0
下载网址:https://nginx.org/en/download.html
解压安装包
[root@nginx nginx-1.24.0]# tar zxf nginx-1.24.0.tar.gz
[root@nginx nginx-1.24.0]# dnf install gcc pcre-devel zlib-devel openssl-devel -y
[root@nginx nginx-1.24.0]# useradd -s /sbin/nologin -M nginx
使用 ./configure 脚本来指定在编译和安装过程中需要包含的各种模块和特性。
[root@nginx nginx-1.24.0]# ./configure
--prefix=/usr/local/nginx \ #设置 Nginx 安装目录为 /usr/local/nginx。
--user=nginx \ #设置 Nginx 运行时使用的用户。
--group=nginx \ #设置 Nginx 运行时使用的组。
--with-http_ssl_module \ #HTTP SSL 模块,用于处理 HTTPS 请求。
--with-http_v2_module \ # HTTP/2 模块。
--with-http_realip_module \ #HTTP real IP 模块,用于获取客户端的真实 IP 地址
--with-http_stub_status_module \ #HTTP stub status 模块,提供基本的服务器监控和健康检查功能。
--with-http_gzip_static_module \ #HTTP gzip static 模块,用于服务预先压缩的文件。
--with-pcre \ # PCRE (Perl Compatible Regular Expressions) 支持,用于正则表达式匹配。
--with-stream \ #TCP/UDP 代理支持。
--with-stream_ssl_module \ #TCP/UDP SSL 模块。
--with-stream_realip_module #TCP/UDP real IP 模块。
[root@nginx nginx-1.24.0]# make && make install
验证版本及编译参数
[root@nginx nginx-1.24.0]# vim ~/.bash_profile

启动服务
[root@nginx nginx-1.24.0]# source ~/.bash profile
[root@nginx nginx-1.24.0]# nginx
平滑升级和回滚实验
[root@nginx nginx-1.24.0]# tar zxf nginx-1.26.1.tar.gz
[root@nginx nginx-1.24.0]# tar zxf echo-nginx-module-0.63.tar.gz
[root@nginx nginx-1.24.0]# cd nginx-1.26.1/
开始编译新版本
[root@nginx nginx-1.26.1]# ./configure
--prefix=/usr/local/nginx
--user=nginx
--group=nginx
--add-module=/root/echo-nginx-module-0.63
--with-http_ssl_module
--with-http_v2_module
--with-http_realip_module
--with-http_gzip_static_module
--with-http_stub_status_module
--with-pcre
--with-stream
--with-stream_ssl_module
--with-stream_realip_module
把之前的旧版的nginx命令备份
[root@nginx nginx-1.24.0]# cd /usr/local/nginx/sbin/
[root@nginx sbin]# cp nginx nginx.24
把新版本的nginx命令复制过去
[root@nginx sbin]# \cp -f /root/nginx/nginx-1.26.1/objs/nginx/usr/local/nginx/sbin
[root@nginx sbin]# nginx -t

回收旧版本

回滚
[root@nginx sbin]# cp nginx nginx.26
[root@nginx sbin]# ls
nginx nginx.24 nginx.26
[root@nginx sbin]# mv nginx.24 nginx
mv: overwrite 'nginx'? y
nginx服务的启动脚本
[root@nginx sbin]# vim /lib/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
重新加载 systemd 服务配置、停止 Nginx 服务并检查 Nginx 进程是否存在。
[root@nginx sbin]# systemctl daemon-reload
[root@nginx sbin]# nginx -s stop
[root@nginx sbin]# ps aux | grep nginx
启用 Nginx 服务并在系统启动时自动启动。
[root@nginx sbin]# systemctl enable --now nginx
[root@nginx sbin]# ps aux | grep nginx
新建一个 PC web 站点
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf

[root@nginx sbin]# vim /usr/local/nginx/conf.d/vhost.conf
server {
listen 80;
server_name www.dc.org;
root /date/web/html;
index index.html;
location /test1 {
root /date/web;
}
}
[root@nginx sbin]# mkdir -p /date/web/html
[root@nginx sbin]# echo www.dc.org > /date/web/html/index.html
[root@nginx sbin]# nginx -t #可以使用 nginx -t 来测试配置文件的语法
[root@nginx sbin]# nginx -s reload

[root@nginx sbin]# vim /usr/local/nginx/conf.d/vhost.conf
server {
listen 80;
server_name www.dc.org;
root /date/web/html;
index index.html;
location /test1 {
root /date/web;
}
location /test2 {
alias /date/web/test1;(软链接)
}
}

location的用法详解
Nginx 的 location 块用于定义如何处理与特定 URL 匹配的请求。这是 Nginx 配置中最常用的部分之一,允许你根据不同的 URL 模式进行细粒度的配置。
1. 基本语法
location [条件] {URL 模式} {
# 配置指令
}
2. URL 模式
-
精确匹配:
location = /exact_url { # ... } -
前缀匹配:
location /prefix_url { # ... }这是最常用的匹配方式,用于匹配以
/prefix_url开头的所有 URL。 -
正则表达式匹配:
location ~ ^/regex_url { # ... } -
非匹配:
location !^~ /regex_url { # ... }这个模式将匹配除了
/regex_url之外的所有 URL。 -
最长匹配:
location /longest_url { # ... }当多个
location块与 URL 匹配时,Nginx 会选择最长的匹配项。
3. 条件
- 等号 (
=): 精确匹配。 - 波浪线 (
~): 正则表达式匹配,区分大小写。 - 波浪线加问号 (
~*): 正则表达式匹配,不区分大小写。 - 波浪线加感叹号 (
!~): 不匹配正则表达式,区分大小写。 - 波浪线加问号加感叹号 (
!~*): 不匹配正则表达式,不区分大小写。
4. 内部指令
-
return: 用于重定向或返回特定的 HTTP 状态码。location /redirect { return 301 https://example.com; } -
proxy_pass: 用于配置反向代理。location /api { proxy_pass http://backend; } -
rewrite: 用于 URL 重写。location /rewrite { rewrite ^/rewrite/(.*)$ /new_url/$1 break; } -
try_files: 用于尝试访问一系列文件或目录。location /static { try_files $uri $uri/ /index.html; } -
error_page: 用于定义错误页面。error_page 404 /404.html; location = /404.html { internal; } -
if: 条件性指令。if ($http_user_agent ~* MSIE) { rewrite ^(.*)$ /msie/$1 break; }
5. 示例
下面是一个简单的 Nginx 配置文件示例,演示了如何使用 location:
server {
listen 80;
server_name example.com;
# 静态文件服务
location / {
root /var/www/html;
index index.html index.htm;
}
# 反向代理
location /api {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 错误页
error_page 404 /404.html;
location = /404.html {
internal;
root /var/www/html;
}
}
注意事项
- 配置文件中的
location块是按照顺序解析的,所以请确保放置的位置正确。 - 如果多个
location块可以匹配同一个 URL,Nginx 将选择最长的前缀匹配或最精确的匹配。 - 使用正则表达式时要谨慎,因为它们可能导致性能下降。
Nginx用户认证
创建认证文件
[root@nginx ~]# htpasswd -cm /usr/local/nginx/.htpasswd dc New password: dc Re-type new password: dc Adding password for user dc
[root@nginx ~]# cat /usr/local/nginx/.htpasswd dc:$apr1$50z25W/R$zGQCFyWmjqHogGxYXQX.m.
再添加一个
[root@nginx ~]# htpasswd -m /usr/local/nginx/.htpasswd chen New password: chen Re-type new password:chen Adding password for user chen
[root@nginx ~]# cat /usr/local/nginx/.htpasswd
dc:$apr1$FyWmjqHogGxYXQX.m50z25W/R$zGQC.
chen:$apr1$qPu3zSj9ANmv2O1pfV6eNKz$2INsDl3
how to use?
[root@nginx ~]# mkdir /data/web/dc
[root@nginx ~]# echo dc > /data/web/dc/index.html
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
listen 80;
server_name www.dc.org;
root /data/web/html;
index index.html;
location /dc {
root /data/web;
auth_basic "login password !!";
ayth_basic_user_file "/usr/local/nginx/.htpasswd";
}
}
[root@nginx ~]# nginx -s reload

自定义错误页面
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
listen 80;
server_name www.dc.org;
root /data/web/html;
index index.html;
error_page 404 /40x.html;
location /dc {
root /data/web;
auth_basic "login password !!";
auth_basic_user_file "/usr/local/nginx/.htpasswd";
}
location = /40x.html{
root /data/web/errorpage;
}
}
[root@nginx ~]# mkdir -p /data/web/errorpage
[root@nginx ~]# echo error!!! > /data/web/errorpage/40x.html
[root@nginx ~]# nginx -s reload

Nginx-自定义日志
[root@nginx ~]# mkdir /var/log/dc.org
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
listen 80;
server_name www.dc.org;
root /data/web/html;
index index.html;
error_page 404 /40x.html;
error_log /var/log/dc.org/error.log;
access_log /var/log/dc.org/access.log;
location /dc {
root /data/web;
auth_basic "login password !!";
auth_basic_user_file "/usr/local/nginx/.htpasswd";
}
location = /40x.html{
root /data/web/errorpage;
}
}
[root@nginx ~]# nginx -s reload
Nginx-检测文件
文件不存在设置跳转到default.html页面
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
listen 80;
server_name www.dc.org;
root /data/web/html;
index index.html index.htm; # 支持更多的索引文件
error_page 404 /40x.html;
error_log /var/log/dc.org/error.log;
access_log /var/log/dc.org/access.log;
try_files $uri $uri/ $uri.html $uri/index.html /error/default.html;
location /dc {
root /data/web;
auth_basic "login password !!";
auth_basic_user_file "/usr/local/nginx/.htpasswd";
}
location = /40x.html {
root /data/web/errorpage;
}
}
[root@nginx ~]# nginx -s reload
[root@nginx ~]# mkdir /data/web/html/error
[root@nginx ~]# echo error default > /data/web/html/error/default.html
[root@nginx ~]# nginx -s reload
Nginx中的长链接管理
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
keepalive_timeout 65 60; #设置 keep-alive 连接的超时时间,第一个值表示空闲超时时间,第二个值表示延迟超时时间。
keepalive_request 100; #限制每个 keep-alive 连接可以处理的最大请求数量。一旦达到这个数量,即使连接还没有超时,Nginx 也会主动关闭该连接。
安装telnet:
[root@nginx ~]# dnf install telnet -y
[root@nginx ~]# curl -v www.dc.org
* Trying 134.40.34.129:80...
* Connected to www.dc.org (134.40.34.129) port 80 (#0)
> GET / HTTP/1.1
> Host: www.dc.org
> User-Agent: curl/7.76.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< content-length: 0
< location: http://hoverstatus.com/
< cache-control: no-cache
< Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
<
* Connection #0 to host www.dc.org left intact
[root@nginx ~]# telnet www.dc.org 80
Trying 134.40.34.129:80...
Connected to www.dc.org.
Escape character is '^]'.
GET / HTTP/1.1
Host: www.dc.org
HTTP/1.1 302 Found
content-length: 0
location: http://hoverstatus.com/
cache-control: no-cache
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Connection closed by foreign host.
Nginx-下载服务器的设定及优化
创一个文件夹,写入数据
[root@nginx ~]# mkdir /data/web/download
[root@nginx ~]# dd if=/dev/zero of=/data/web/download/dcfile bs=1M count=100
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
listen 80;
server_name www.dc.org;
root /data/web/html;
index index.html;
error_page 404 /40x.html;
error_log /var/log/dc.org/error.log;
access_log /var/log/dc.org/access.log;
try_files $uri $uri.html $uri/index.html /error/default.html;
location /dc {
root /data/web;
auth_basic "login password !!";
auth_basic_user_file "/usr/local/nginx/.htpasswd";
}
location = /40x.html{
root /data/web/errorpage;
}
location /download {
root /data/web;
autoindex on;
}
}
[root@nginx ~]# nginx -s reload
Nginx 状态页
[root@nginx ~]# cd /usr//local/nginx/conf.d/
[root@nginx conf.d]# vim status.conf
server {
listen 80;
server_name dc.dc.org;
root /data/web/html;
index index.html;
location /status {
stub_status;
allow 172.25.254.1;
deny all;
}
}
root@nginx conf.d]# nginx -s reload

Nginx的数据压缩功能
[root@nginx conf.d]# vim /usr/local/nginx/conf/nginx.conf
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_http_version 1.1;
gzip_vary on;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/gif image/png;
[root@nginx conf.d]# nginx -t
[root@nginx conf.d]# nginx -s reload
[root@nginx conf.d]# echo hello hxhx > /data/web/html/small.html
[root@nginx conf.d]# du -sh /usr/local/nginx/logs/
[root@nginx conf.d]# cat /usr/local/nginx/logs/access.log > /data/web/html/big.html
检测
[root@nginx conf.d]# curl --head --compressed 172.25.254.100/small.html
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Sat, 17 Aug 2024 08:46:57 GMT
Content-Type: text/html
Content-Length: 11
Last-Modified: Sat, 17 Aug 2024 08:40:55 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "66c06217-b"
Accept-Ranges: bytes
[root@nginx conf.d]# curl --head --compressed 172.25.254.100/big.htm
1203

被折叠的 条评论
为什么被折叠?



