nginx笔记-v1.22.1
nginx 是一个HTTP和反向代理web服务器,同时还提供了IMAP/POP3/SMTP 邮箱代理服务和通用 TCP/UDP 代理服务
(转自 nginx 官网),是企业中常见的 web 应用服务器
常见的 web 服务器还有如下几种:
- Apache
- nginx
- IIS 应用于 Windows 系统的 web服务器
- GWS 亚马逊开发的
- Weblogic
nginx 相较于其它 web 服务器有如下优势:
- 高性能高 - 采用了多进程和 I/O 多路复用 (epoll) 的底层实现,响应速度快,高并发处理能力强
- 扩展性强 - 模块化设计极具扩展性,能够根据企业不同的业务需求,通过配置文件的配置来添加各个业务的定制模块
- 支持热部署 - 可以在 nginx 不停止工作的情况下,对 nginx 进行版本升级、更新配置和更换日志文件等功能
- 开源,成本低 - 采用类似 BSD 的开源许可证,可以免费将 nginx 应用于商业领域,而且还可以定制化修改 nginx 源码来实现特殊需求
nginx 的应用场景主要有以下几种:
- 静态资源服务 - 直接返回请求的静态资源文件,减轻Web服务器负担
- 负载均衡 - 实现集群化管理
- 反向代理 - 提高Web服务器的安全性,隐藏Web服务器的真实IP
- 资源缓存 - 缓存Web服务器返回的响应,减少对Web服务器的请求
- 安全控制 - 针对用户访问进行权限控制,https 加密处理的安全认证,结合Lua实现waf防护 (网页防火墙) 防cc攻击、sql注入
一. nginx 安装部署及基本命令
文中所有命令都是通过 root 用户执行的,如果没有相应的权限,需要考虑使用
sudo
获取 root 权限
1. 环境准备
需要 gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel 依赖
# centos 使用 yum 安装
yum install -y gcc gcc-c++
yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel
# ubuntu 使用 apt 安装
apt install -y gcc g++
apt install -y libpcre3 libpcre3-dev
apt install -y zlib1g zlib1g-dev
apt install -y openssl libssl-dev
下载 nginx tar 包
2. 安装 nginx
解压到自定义的目录 (这里解压到已经创建好的 /usr/app/
目录)
# 解压 tar 包
tar -zxvf /opt/tar-repository/nginx-1.22.1.tar.gz -C /usr/app/
mkdir /usr/app/nginx-1.22.1/ngx
# 创建 nginx 软连接
ln -s /usr/app/nginx-1.22.1/ngx /usr/local/nginx
# 进入该目录
cd /usr/local/nginx
预编译,可以指定一些参数,这里指定 prefix 生成文件到当前 nginx 的目录
# 配置生成的服务器文件路径,默认为 /usr/local/nginx
# 这里需要 ssl 支持,所以添加了 --with-http_ssl_module
./configure --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/nginx.conf --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module
--with-threads
# 可以创建 nginx 专用的 Linux 账户
# groupadd -g 30 -o -r ngx
# useradd -M -N -g ngx -o -r -d /usr/local/nginx -s /bin/false -c "nginx Server" -u 30 ngx
# chown ngx:ngx -R /usr/local/nginx/
# ./configure --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/nginx.conf --user=ngx --group=ngx --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module --with-threads
可指定的参数参考官网 通过 source 安装 - configure
编译并安装 nginx
make & make install
创建 nginx 环境变量配置
vim /etc/profile.d/env-nginx.sh
输入并保存以下内容
# nginx server envrionment variable
export NGX_HOME=/usr/local/nginx
export PATH=$PATH:$NGX_HOME/sbin
重新加载 profile
source /etc/profile
输入以下命令查看 nginx 版本
# 查看 nginx 版本信息,包括配置参数
nginx -V
# 或者使用简单版本信息的命令
# nginx -v
3. nginx 基本命令
(1) 查看帮助信息
# 查看帮助信息
nginx -help
可以通过该命令查看所有命令用法
nginx -help
nginx version:nginx/1.22.1
Usage:nginx [-?hvVtTq] [-s signal] [-p prefix]
[-e filename] [-c filename] [-g directives]
Options:
-?,-h :this help
-v :show version and exit
-V :show version and configure options then exit
-t :test configuration and exit
-T :test configuration,dump it and exit
-q :suppress non-error messages during configuration testing
-s signal :send signal to a master process:stop,quit,reopen,reload
-p prefix :set prefix path (default:/usr/local/nginx/)
-e filename :set error log file (default:logs/error.log)
-c filename :set configuration file (default:/usr/local/nginx/nginx.conf)
-g directives :set global directives out of configuration file
(2) 启动 nginx
# 启动 nginx,默认服务端口号 80 ,只需访问本机 ip 即可
# 默认配置文件为/usr/local/nginx/nginx.conf
# (来自 --conf-path=/usr/local/nginx/nginx.conf 的配置,nginx -V 可查看)
nginx
# 或者指定配置文件启动 nginx
nginx -c NGINX_CONFIG_FILENAME
# 如果 NGINX_CONFIG_FILENAME 这个文件不在默认 prefix 路径下,启动时则需要指定 -p 选项
# 而且在使用 -s 进行停止或重加载时都要带有 -p 选项
nginx -p NGINX_CONFIG_PREFIX -c NGINX_CONFIG_FILENAME
# 启动前可以使用 -t 选项测试配置文件的正确性 (不会真正启动 nginx 服务)
nginx -t [-c NGINX_CONFIG_FILENAME]
(3) 停止 nginx
# 强行停止 nginx
nginx -s stop
# 优雅停止 nginx
# 运行该命令会先等待工作进程完成当前请求的服务,然后再停止nginx进程
nginx -s quit
# 也可以使用 kill -QUIT PID 命令停止 nginx
# pid 一般保存在 ${prefix}/logs/nginx.pid 文件中
(4) 重新加载 nginx 配置
# 重新加载 nginx 配置
nginx -s reload
nginx 的基础控制命令可以参考 官方文档 Starting,Stopping,and Reloading Configuration
二. nginx 目录结构与配置文件
1. nginx 目录结构
通过 tree 命令获取 nginx 安装路径下的目录结构
# 需要安装依赖 yum install -y tree
tree -aF /usr/local/nginx/
/usr/local/nginx/ #
├── client_body_temp/ #
├── fastcgi.conf #
├── fastcgi.conf.default #
├── fastcgi_params # nginx 与 PHP 交互的内置变量
├── fastcgi_params.default # nginx 与 PHP 交互的内置变量 (默认配置备份)
├── fastcgi_temp/ #
├── html/ # nginx 默认的静态资源目录
│ ├── 50x.html # nginx 默认错误页面
│ └── index.html # nginx 默认静态页面
├── koi-utf #
├── koi-win #
├── logs/ # nginx 日志目录
│ ├── access.log # nginx 访问日志文件
│ └── error.log #
├── mime.types # nginx 响应类型
├── mime.types.default # nginx 响应类型 (默认配置备份)
├── nginx.conf # nginx 主配置文件
├── nginx.conf.default # nginx 主配置文件 (默认配置备份)
├── proxy_temp/ #
├── sbin/ # nginx 命令可执行文件目录
│ └── nginx* # nginx 命令可执行文件
├── scgi_params #
├── scgi_params.default #
├── scgi_temp/ #
├── uwsgi_params # nginx 与 uwsgi 交互的内置变量
├── uwsgi_params.default # nginx 与 uwsgi 交互的内置变量 (默认配置备份)
├── uwsgi_temp/ #
└── win-utf #
2. nginx 配置文件
官网对配置文件结构的说明:
nginx 配置文件的结构 - Configuration File’s Structure
这里以 nginx 安装路径下的默认主配置文件举例说明
#user nobody; # 指定 nginx 服务的用户
worker_processes 1; # 定义 nginx 的 worker 线程数
#error_log logs/error.log; # 指定 nginx 的 error.log 文件路径,默认在 ${prefix}/logs/error.log
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid; # 指定 nginx 的 pid 文件路径,默认在 ${prefix}/logs/nginx.pid
events { # ※ events 模块
worker_connections 1024; # 指定
}
http { # ※ http 模块
include mime.types; # 引用文件中的内容,可用 路径/*.xxx 的方式指定某路径下满足格式的条件
default_type application/octet-stream; # 默认响应类型
# 定义日志输出格式: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 访问日志文件位置:access_log log文件位置 格式名
sendfile on; # 定义是否发送文件
#tcp_nopush on; #
#keepalive_timeout 0;
keepalive_timeout 65; # nginx 建立 TCP 连接后,超过该时长自动断开连接,单位秒(s)
#gzip on; # 是否对请求中的文件进行压缩处理
server { # ※ server 模块
listen 80; # 当前站点监听的端口号
server_name localhost; # 当前站点的 ip 或域名
#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 配置示例
1. 一个简单的 nginx 服务
新建一个文件夹,用于存放访问资源,并且创建一个 test.html
文件和一个新的配置文件 nginx-test.conf
cd /usr/local/nginx
mkdir web
touch web/test.html
touch nginx-test.conf
注意,自定义的 nginx 配置文件需要放在安装 nginx 时指定的 prefix 目录 (这里即
/usr/local/nginx
目录) 下 ( 可通过nginx -V
查看 prefix 的值 ),否则 在启动/停止/重载 nginx 服务时均需 -p 选项指定服务文件根路径
在 test.html
中随意写一些内容并保存
这是一个名为 test 的 HTML 文件
然后配置 nginx-test.conf
如下
#user ngx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 60;
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root web;
index test.html;
}
}
}
使用 nginx -c
命令指定 nginx-test.conf 配置文件启动 nginx
nginx -c nginx-test.conf
访问 http://${IP}
即可看到响应的 test.html
的内容
2. 在 nginx 中添加多个 server
在 /usr/local/nginx/web
文件夹下多创建两个 HTMl 文件
cd /usr/local/nginx
touch web/test1.html
touch web/test2.html
test2.html
和 test2.html
内容分别如下
<!-- test1.html -->
这是一个名为 test1 的 HTML 文件,监听 80 端口,域名 www.test.com
<!-- test2.html -->
这是一个名为 test2 的 HTML 文件,监听 8800 端口,域名 localhost
修改 nginx-test.conf
vim nginx-test.conf
修改为以下内容
#user ngx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 60;
server {
listen 80;
server_name www.abc.com;
charset utf-8;
location / {
root web;
index test.html;
}
}
server {
listen 80;
server_name www.test.com;
charset utf-8;
location / {
root web;
index test1.html;
}
}
server {
listen 8800;
server_name www.abc.com;
charset utf-8;
location / {
root web;
index test2.html;
}
}
}
注意,上面的 conf 中添加了三个 server,listen、server_name 和 访问资源各有区别
- 监听端口:80,server_name:www.abc.com,访问资源:test.html
- 监听端口:80,server_name:www.test.com,访问资源:test1.html
- 监听端口:8800,server_name:www.abc.com,访问资源:test2.html
在访问 nginx 的电脑上配置 hosts 映射
以 windows 系统举例,找到 C:\Windows\System32\drivers\etc\hosts
文件并以管理员身份打开,将以下内容追加到 hosts 文件末尾 ( ${IP}
部分替换为 nginx 所在服务器的 ip ) 然后保存
# nginx 服务器 DNS 映射,${IP} 部分替换为 nginx 所在服务器的 ip
${IP} www.test.com
使用 Win + R 键打开 [运行]
对话框,输入 cmd
点击确定,打开命令行窗口,输入以下命令刷新 DNS 解析缓存
ipconfig /flushdns
重新启动 nginx
nginx -s quit
nginx -c nginx-test.conf
# 也可以用 nginx -s reload 重新加载 nginx
分别访问 http://${IP}
,http://www.test.com
,http://${IP}:8800
,能看到三个不同的页面
3. nginx 请求流程
由上面的多 server 配置示例不难看出,nginx 的 server 是由 listen 定义的端口 和 server_name 区分的
而两个配置 server_name 为 www.abc.com 的 server 明显与域名不符合 ( 直接通过 ip 请求,而非域名 ),确也能访问到各自对应的 index 页
由此,nginx 服务的访问 url 有两同不同的方式 ( 看似没有 port 实际是省略了 http 协议的默认 80 端口号 )
ip:port 访问
域名:port 访问
向 nginx 发送请求有大致如下几个过程:
- 浏览器输入 url ( ip:port/PATH 或 域名:port/PATH )
- 如果输入的 url 里不包括协议类型,则浏览器添加协议类型,如 http,https
- 发起 TCP 连接,发送报文
- 监听对应端口的 nginx 接收到报文,通过报文中的请求的域名和配置了该监听端口的所有 server 中的 server_name 进行匹配,决定由哪个 server 进行处理
- 决定好 server 后,由该 server 将去掉 ip /域名 和 端口号后的路径和多个 location 匹配,找到最匹配的 location,按照内部的规则去访问资源 ( 请求静态资源/代理/其它… )
- 获取到对应的资源后,封装为响应返回给请求方
上述流程在 官网 Serving Static Content 中有所体现,简单说明了配置文件的内容对于静态资源请求 nginx 流程的作用
3. nginx 功能性配置
(1) nginx 访问控制
( nginx.org 官网 ngx_http_access_module )
nginx 通过访问配置,可以根据 ip 等信息判断是否放行请求
可以在 server 或者 location 中配置多个 allow 或 deny 指令,配置的所有指令会从上向下匹配直到满足访问条件,allow 配置允许访问的条件,deny 配置禁止访问的条件,例如
# 只允许IPv4网络10.1.1.0/16和192.168.1.0/24访问,IPv6网络2001:0db8::/32访问。
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
配置 allow 或 deny 允许配置 all / ip(可带掩码) / ipv6(可带掩码) / socket,允许配置的块包括 http,server,location,limit_except
Syntax: allow address | CIDR | unix:| all;
Default: —
Context: http,server,location,limit_except
Syntax: deny address | CIDR | unix:| all;
Default: —
Context: http,server,location,limit_except
如果有更为复杂的访问规则,推荐使用 ngx_http_geo_module 模块的指令进行配置
(2) nginx 自动文件索引
( nginx.org 官网 ngx_http_access_module )
nginx 支持将指定路径以文件树的形式响应,通过 autoindex 指令配置
执行以下命令,创建好一些空文件和目录
cd /usr/local/nginx
mkdir web/list
cd web/list
mkdir {1..5}
cd 2
touch {1..3}
修改 nginx-test.conf
,内容如下
#user ngx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 60;
server {
listen 80;
server_name www.test.com;
charset utf-8;
deny all;
location / {
root web;
index test.html;
}
location /list {
#alias web/list;
root web;
autoindex on;
autoindex_exact_size off;
autoindex_format html;
autoindex_localtime on;
}
}
}
- autoindex on | off - 是否开启自动索引,默认 off
- autoindex_exact_size on | off - 是否开启自动索引,默认 off
- autoindex_format html | xml | json | jsonp - 设置目录列表的格式,当使用 jsonp 格式时,用回调请求参数设置回调函数的名称;如果参数缺失或值为空,则使用 json 格式
- autoindex_localtime on | off - 对于 HTML 格式,指定以本地时区或UTC输出目录清单中的时间,默认 off 按 UTC 时间
alias 和 root 的区别
alias 是将请求中 location 的内容替换为 alias 后定义的内容,例如
location /i/ { alias /data/w3/images/; }
当以
/i/test.jpg
请求上面的 location 时,会替换为请求/data/w3/images/test.jpg
这个资源如果 location 的配置中包含正则,则在 alias 中也应当包含匹配项,否则会被替换掉,如下
location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ { alias /data/w3/images/$1; }
路径值可以包含变量,除了
$document_root
和$realpath_root
对于上面的
/i/test.jpg
请求,官网推荐采用 root 配置,配置如下location /i/ { root /data/w3; }
更多有关 alias 指令的用法参考 nginx alias 别名的使用
root 是设置请求的资源所在的根目录,例如:
location /i/ { root /data/w3; }
按照上面的 location ,如果请求
/i/test.jpg
,会去请求/data/w3
目录下寻找./i/test.jpg
文件,即请求/data/w3/i/test.jpg
这个资源路径值可以包含变量,除了
$document_root
和$realpath_root
文件的路径仅是通过向 root 指令的值添加一个URI来构造的,如果必须修改URI,则应该使用 alias 指令
(3) nginx Basic 安全认证
( nginx.org 官网 ngx_http_auth_basic_module )
nginx 可以通过 auth_basic 和 auth_basic_user_file 指令配置 HTTP Baisc 身份验证协议验证用户名和密码来限制对资源的访问
官网说明了使用 auth_basic 时,需要对用户文件中的密码通过 encrypt()
函数进行加密,可以采用 Apache HTTP Server 发行版中的 htpasswd 工具或 openssl passwd 命令生成
先创建好放置用户名密码的文件
cd /usr/local/nginx
mkdir -P conf
touch passwd
-
htpasswd 生成 user:password
安装 httpd-tools 依赖包
yum install -y httpd-tools
安装后可以使用 htpasswd 命令将自定义的用户名密码以
用户名:密码
的形式# -c 按照路径新建文件 # htpasswd [-c] 用户密码文件路径 用户名 htpasswd conf/passwd admin1 # 输入两次密码
-
openssl passwd 生成 password
openssl 和 openssl-devel 依赖在安装 nginx 之前已经安装,应该已有 openssl 命令,使用
openssl passwd
生成密码加密后的字符串# -1 对加密后的密码进行 md5 摘要 # openssl passwd [-1] '密码' # 配置不用 md5 摘要的密码 (没有 -1) 也可以 echo "admin2:`openssl passwd -1 'password'`" >> conf/passwd # 返回的密码内容,手动写入 conf/passwd
上面两种方式如果都执行了,就可以通过 admin1 和 admin2 两个用户登录
在 nginx-test.conf 文件中配置如下
#user ngx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 60;
server {
listen 80;
server_name www.test.com;
charset utf-8;
location / {
auth_basic 'test.com';
auth_basic_user_file conf/passwd;
root web;
index test.html;
}
}
}
-
auth_basic string | off - 如果配置为 off 则会取消从上一个配置级别继承的启用;否则,参数内容会被作为 Basic 认证的 realm (认证域名),且参数值可以包含变量
-
auth_basic_user_file file - 指定保存用户名和密码的文件,文件名可以包含变量,文件格式如下:
# 注释 name1:password1 name2:password2:注释 name3:password3
重新启动 nginx 保证配置已被加载
再次通过浏览器访问 www.test.com
时会发现需要输入用户名/密码验证
(4) nginx 服务状态检查
( nginx.org 官网 ngx_http_stub_status_module )
要使用该功能,必须保证安装 nginx 时添加了 http_stub_status_module 模块 (如未添加需要重新执行 configure 和 make,不能执行 make install (会把原有内容覆盖))
nginx -V
nginx version:nginx/1.22.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments:--prefix=/usr/local/nginx --conf-path=/usr/local/nginx/nginx.conf --user=ngx --group=ngx --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module --with-threads
nginx-text.conf 配置如下
#user ngx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 60;
server {
listen 80;
server_name www.test.com;
charset utf-8;
location / {
auth_basic 'test.com';
auth_basic_user_file conf/passwd;
root web;
index test.html;
}
location = /status {
stub_status;
}
}
}
- stub_status - 配置该指令即可通过该 location 获取服务状态,也可以配置在 server 块指定端口用于获取状态
在 nginx 1.7.5 之前的版本中,stub_status 指令语法需要一个任意参数,例如
stub_status on
location = /status 是 location 的精确匹配,即只有访问
/status
时才会进入该 location
启动 nginx 并访问 http://www.test.com/status
就可以看到当前 nginx 的服务状态信息
http_stub_status_module 模块提供的信息如下:
-
Active connections
当前活跃连接数,包括正在等待的连接 (实时值)
-
accepts
接受的客户端连接的总数 (累计值)
-
handled
已处理的连接总数,通常与 accepts 的值相同,除非达到某些资源限制(例如,worker_connections 限制) (累计值)
-
requests
客户端请求的总数 (累计值)
-
Reading
nginx 读取请求头的当前连接数 (与 worker 数相关)
-
Writing
nginx 将响应写回客户端的当前连接数 (与 worker 数相关)
-
Waiting
当前等待请求的空闲客户端连接数,这个数量不能过多,如果很多表示
ngx_http_stub_status_module 模块支持以下嵌入式变量
$connections_active
- Active connections 的值$connections_reading
- Reading 的值$connections_writing
- Writing 的值$connections_waiting
- Waiting 的值
(5) nginx location 路径匹配模式
( nginx.org 官网 ngx_http_core_module ,location 指令 )
location 用于根据请求 URI 设置配置
location 配置语法如下
location [ = | ~ | ~* | ^~ ] uri {
...
}
在不适用 ^~
的情况下,可以在 uri
的位置使用正则表达式匹配
location 的匹配模式分为四种:
写法 | 说明 |
---|---|
= | 精确匹配 |
~ | 精确匹配 ( 区分大小写 ) |
~* | 精确匹配 ( 不区分大小写 ) |
^~ | uri 优先匹配 ( 不支持正则表达式 ) |
nginx-test.conf 文件内容如下
#user ngx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 60;
server {
listen 80;
server_name www.test.com;
charset utf-8;
location / {
root web;
index test.html;
}
location = /status {
stub_status;
}
}
}
对 /status
接口的 location 配置说明四种匹配模式
-
设置为
location = /status
精确匹配模式下,必须保证 uri 和 location 完全一致,否则均不可访问
此时
www.test.com/status
可以正常访问,www.test.com/status/
、www.test.com/status/1
、www.test.com/STATUS/
、www.test.com/STATUS/1
均不能访问 ( 浏览器导航栏可能会自动将大写转为小写后请求,可以使用curl
验证 ) -
设置为
location ~ /status
模糊匹配模式下,uri 只要满足以 location 开头即可,但是区分 uri 大小写
此时
www.test.com/status
、www.test.com/status/
、www.test.com/status/1
可以正常访问,www.test.com/STATUS/
、www.test.com/STATUS/1
不能访问 ( 浏览器导航栏可能会自动将大写转为小写后请求,可以使用curl
验证 ) -
设置为
location ~* /status
该匹配模式下,uri 要满足以 location 开头且不区分 uri 大小写
此时
www.test.com/status
、www.test.com/status/
、www.test.com/status/1
、www.test.com/STATUS/
、www.test.com/STATUS/1
均可以正常访问 -
server 块如下配置
server { listen 80; server_name www.test.com; charset utf-8; location ~ /status { return stub_status; } location ~* /status { return 403; } location ^~ /status { return 500; } location = /status { stub_status; } }
- 访问
www.test.com/status
可正常响应,说明=
匹配优先级最高 - 访问
www.test.com/status/
、www.test.com/status/1
返回 500,说明^~
比~*
和~
都具有更高优先级; - 访问
www.test.com/STATUS/
、www.test.com/STATUS/1
返回 403,说明~*
可以忽略大小写,而~
、^~
和=
都不能
- 访问
上例说明同样 uri 下,优先级从高到低:=
> ^~
> ( ~
| ~*
)
uri 部分一致时,优先级从高到低 ^~
> ( ~
| ~*
),能匹配到更多的 uri 的 location 优先级更高,其余由配置的前后顺序决定
(6) nginx alias 别名的使用
( nginx.org 官网 ngx_http_core_module,location 指令 )
alias 是将请求中 location 的内容替换为 alias 后定义的内容,例如:
location /i/ {
alias /data/w3/images/;
}
当以 http://host:port/i/test.jpg
请求上面的 location 时,会替换为请求 http://host:port/data/w3/images/test.jpg
这个资源
如果按照如下配置:
location /i/ { alias /data/w3/images; }
当以
http://host:port/i/test.jpg
请求上面的 location 时,会替换为请求http://host:port/data/w3/imagestest.jpg
这个资源,注意 URI 中缺少了一级/
如果 location 的配置中包含正则,则在 alias 中也应当包含匹配项,否则会被替换掉,如下
location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ {
alias /data/w3/images/$1;
}
路径值可以包含变量,除了 $document_root
和 $realpath_root
对于单纯将一个路径下的资源改为访问另一个路径下的资源,官网推荐采用 root 配置,配置如下
location /i/ {
root /data/w3;
}
同一 location 块中 root 和 alias 只能设置一个
(7) nginx 配置 return 返回或跳转
nginx.org 官网 ngx_http_rewrite_module ,return 指令
return 可以配置在 server、location 或 location 的 if 中
- return code [text];
- return code URL;
- return URL;
code 中可以返回响应码,并且可以通过 text 定义返回的内容
如果 code 定义为 30x 并且指定一个URL,或者直接 return 一个URL,( URL 为完整路径,如 http://www.example.com
或 https://www.example.com
),就会进行跳转
在同一指令块中,return 后的所有配置都不会生效
(8) nginx 配置 rewrite 重写 URI
nginx.org 官网 ngx_http_rewrite_module ,rewrite 指令
一般用于服务器资源调整后重新定位资源
rewrite 可以配置在server、location、if,语法如下:
rewrite regex replacement [flag];
flag 参数可以是以下四个的任一:
- last
- break
- permanent
- redirect