基本结构
main # 全局配置
├── events # nginx工作模式
├── http
│ ├── upstream # 负载均衡服务器设置
│ ├── server # 主机设置
│ │ ├── location # url匹配
主要配置含义
main区域配置:
user root;
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;
}
user :来指定Nginx Worker进程运行用户以及用户组,默认由nobody账号运行。
worker_processes:来指定了Nginx要开启的子进程数。每个Nginx进程平均耗费10M~12M内存。根据经验,一般指定1个进程就足够了,如果是多核CPU,建议指定和CPU的数量一样的进程数即可。我这里写2,那么就会开启2个子进程,总共3个进程。
error_log:用来定义全局错误日志文件。日志输出级别有debug、info、notice、warn、error、crit可供选择,其中,debug输出日志最为最详细,而crit输出日志最少。
pid:用来指定进程id的存储文件位置cat查看里面是nginx的主程PID。
worker_connections:#工作进程的最大连接数量 理论上每台nginx服务器的最大连接数为worker_processes*worker_connections worker_processes为我们再main中开启的进程数。
nginx.conf 配置文件的语法规则
1.配置文件由指令与指令块构成
2.每条指令以 “;” 分号结尾,指令与参数间以空格符号分隔
3.指令块以 {} 大括号将多条指令组织在一起
4.include 语句允许组合多个配置文件以提升可维护性
5.通过 # 符号添加注释,提高可读性
6.通过 $ 符号使用变量
7.部分指令的参数支持正则表达式,例如常用的 location 指令
内置变量
常用命令
./nginx -s reload # 向主进程发送信号,重新加载配置文件,热重启
./nginx -s reopen # 重启 Nginx
./nginx -s stop # 快速关闭
./nginx -s quit # 等待工作进程处理完成后关闭
./nginx -T # 查看当前 Nginx 最终的配置
./nginx -t -c <配置路径> # 检查配置是否有问题,如果已经在配置目录,则不需要 -c
配置 nginx 开机自启
创建并打开 nginx.service 文件:
vi /lib/systemd/system/nginx.service
内容如下:
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
:wq 保存退出,运行 systemctl daemon-reload 使文件生效。
systemctl enable nginx.service # 设置开机启动
systemctl disable nginx.service # 停止开机自启动
配置 nginx 全局可用
1、编辑 /etc/profile
vi /etc/profile
2、在最后一行添加配置,:wq 保存
export PATH=$PATH:/usr/local/nginx/sbin
3、使配置立即生效
source /etc/profile
反向代理
server {
#监听80端口
listen 80;
#配置基于名称的虚拟主机(支持精准匹配,*通配符,正则表达式)
server_name localhost;
# 所有 /api 下的接口访问都代理到本地的 9999 端口
location /api {
proxy_pass http://127.0.0.1:9999;
}
# 所有 /api-other 下的接口访问都代理到本地的 8888 端口
location /api-other {
proxy_pass http://127.0.0.1:8888;
}
}
访问控制
server {
location ~ ^/index.html {
# 禁止 192.168.1.1 和 192.168.1.2 两个 ip 访问,其它全部允许。从上到下的顺序,匹配到便跳出
deny 192.168.1.1;
deny 192.168.1.2;
allow all;
}
}
负载均衡
http {
# 轮询策略(默认)
upstream test.com {
server 192.168.1.12:8887;
server 192.168.1.13:8888;
}
server {
location /api {
proxy_pass http://test.com;
}
}
}
http {
# 根据服务器权重
upstream test.com {
server 192.168.1.12:8887 weight=9;
server 192.168.1.13:8888 weight=1;
}
server {
location /api {
proxy_pass http://test.com;
}
}
}
http {
# 客户端 ip 绑定(ip_hash)
# 来自同一个 ip 的请求永远只分配一台服务器,有效解决了动态网页存在的 session 共享问题。
upstream test.com {
ip_hash;
server 192.168.1.12:8887;
server 192.168.1.13:8888;
}
server {
location /api {
proxy_pass http://test.com;
}
}
}
http {
# 最小连接数策略
# 将请求优先分配给压力较小的服务器
upstream test.com {
least_conn;
server 192.168.1.12:8887;
server 192.168.1.13:8888;
}
server {
location /api {
proxy_pass http://test.com;
}
}
}
gzip 压缩
开启 gzip 压缩可以大幅减少 http 传输过程中文件的大小,可以极大的提高网站的访问速度,基本是必不可少的优化操作:
http {
gzip on; # 开启gzip 压缩
}
HTTP 服务器
server {
listen 80;
server_name localhost;
location / {
root /usr/local/app;
index index.html;
}
}
动静分离
# 所有静态请求都由nginx处理,存放目录为 html
location ~ \.(gif|jpg|jpeg|png|bmp|swf|css|js)$ {
root /usr/local/resource;
expires 10h; # 设置过期时间为10小时
}
# 所有动态请求都转发给 tomcat 处理
location ~ \.(jsp|do)$ {
proxy_pass 127.0.0.1:8888;
}
请求限制
对于大流量恶意的访问,会造成带宽的浪费,给服务器增加压力。可以通过 nginx 对于同一 IP 的连接数以及并发数进行限制。合理的控制还可以用来防止 DDos 和 CC 攻击。
关于请求限制主要使用 nginx 默认集成的 2 个模块:
limit_conn_module 连接频率限制模块
limit_req_module 请求频率限制模块
涉及到的配置主要是:
limit_req_zone 限制请求数
limit_conn_zone 限制并发连接数
正向代理
正向代理,意思是一个位于客户端和原始服务器(origin server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后代理向原始服务器转交请求并将获得的内容返回给客户端。正向代理的对象是客户端,服务器端看不到真正的客户端。反向代理代理的对象是服务端,客户端看不到真正的服务端。
resolver 8.8.8.8 # 谷歌的域名解析地址
server {
resolver_timeout 5s; // 设超时时间
location / {
# 当客户端请求我的时候,我会把请求转发给它
# $host 要访问的主机名 $request_uri 请求路径
proxy_pass http://$host$request_uri;
}
}
图片防盗链
server {
listen 80;
server_name *.test;
# 图片防盗链
location ~* \.(gif|jpg|jpeg|png|bmp|swf)$ {
valid_referers none blocked server_names ~\.google\. ~\.baidu\. *.qq.com; # 只允许本机 IP 外链引用,将百度和谷歌也加入白名单有利于 SEO
if ($invalid_referer){
return 403;
}
}
}
适配 PC 或移动设备
server {
listen 80;
server_name test.com;
location / {
root /usr/local/app/pc; # pc 的 html 路径
if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
root /usr/local/app/mobile; # mobile 的 html 路径
}
index index.html;
}
}
配置 HTTPS
server{
listen 443 ssl http2; // 这里还启用了 http/2.0
ssl_certificate /etc/letsencrypt/live/test.com/fullchain.pem; # 证书文件地址
ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem; # 私钥文件地址
server_name test.com www.test.com; // 证书绑定的域名
}
配置 HTTP 转 HTTPS
以上配置选择自己需要的一条即可,不用全部加
server {
listen 80;
server_name test.com www.test.com;
# 单域名重定向
if ($host = 'www.sherlocked93.club'){
return 301 https://www.sherlocked93.club$request_uri;
}
# 全局非 https 协议时重定向
if ($scheme != 'https') {
return 301 https://$server_name$request_uri;
}
# 或者全部重定向
return 301 https://$server_name$request_uri;
}
代理缓存
# nginx 提供一块 10 M 的内存用于缓存,名字为 my_cache, levels 等级为 1:2,缓存存放的路径为 usr/local/cache。
proxy_cache_path usr/local/cache levels=1:2 keys_zone=my_cache:10m;
server {
listen 80;
server_name test.com;
location / {
proxy_cache my_cache;
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;
}
}
访问日志
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 logs/access.log main;
}
静态资源服务器
server {
listen 80;
server_name static.bin;
charset utf-8; # 防止中文文件名乱码
location /download {
alias /usr/share/nginx/static; # 静态资源目录
autoindex on; # 开启静态资源列目录,浏览目录权限
autoindex_exact_size off; # on(默认)显示文件的确切大小,单位是byte;off显示文件大概大小,单位KB、MB、GB
autoindex_localtime off; # off(默认)时显示的文件时间为GMT时间;on显示的文件时间为服务器时间
}
}
附 nginx 内置预定义变量
按字母顺序,变量名与对应定义:
$arg_PARAMETER #GET 请求中变量名 PARAMETER 参数的值
$args #这个变量等于 GET 请求中的参数,例如,foo=123&bar=blahblah;这个变量可以被修改
$binary_remote_addr #二进制码形式的客户端地址
$body_bytes_sent #传送页面的字节数
$content_length #请求头中的 Content-length 字段
$content_type #请求头中的 Content-Type 字段
$cookie_COOKIE #cookie COOKIE 的值
$document_root #当前请求在 root 指令中指定的值
$document_uri #与 $uri 相同
$host #请求中的主机头(Host)字段,如果请求中的主机头不可用或者空,则为处理请求的 server 名称(处理请求的 server 的 server_name 指令的值)。值为小写,不包含端口
$hostname #机器名使用 gethostname 系统调用的值
KaTeX parse error: Expected 'EOF', got '#' at position 13: http_HEADER #̲HTTP 请求头中的内容,HE…http_user_agent(Uaer-Agent 的值)
$sent_http_HEADER #HTTP 响应头中的内容,HEADER 为 HTTP 响应中的内容转为小写,-变为_(破折号变为下划线),例如:[公式]sent_http_content_type…
$is_args #如果 $args 设置,值为"?",否则为""
$limit_rate #这个变量可以限制连接速率
$nginx_version #当前运行的 nginx 版本号
$query_string #与 $args 相同
$remote_addr #客户端的 IP 地址
$remote_port #客户端的端口
$remote_port #已经经过 Auth Basic Module 验证的用户名
$request_filename #当前连接请求的文件路径,由 root 或 alias 指令与 URI 请求生成
$request_body #这个变量(0.7.58+)包含请求的主要信息。在使用 proxy_pass 或 fastcgi_pass 指令的 location 中比较有意义
$request_body_file #客户端请求主体信息的临时文件名
$request_completion #如果请求成功,设为"OK";如果请求未完成或者不是一系列请求中最后一部分则设为空
$request_method #这个变量是客户端请求的动作,通常为 GET 或 POST。包括 0.8.20 及之前的版本中,这个变量总为 main request 中的动作,如果当前请求是一个子请求,并不使用这个当前请求的动作
$request_uri #这个变量等于包含一些客户端请求参数的原始 URI,它无法修改,请查看 $uri 更改或重写 URI
KaTeX parse error: Expected 'EOF', got '#' at position 8: scheme #̲所用的协议,例如 http 或…$scheme://example.com$1 redirect
$server_addr #服务器地址,在完成一次系统调用后可以确定这个值,如果要绕开系统调用,则必须在 listen 中指定地址并且使用 bind 参数
$server_name #服务器名称
$server_port #请求到达服务器的端口号
$server_protocol #请求使用的协议,通常是 HTTP/1.0、HTTP/1.1 或 HTTP/2
$uri #请求中的当前 URI(不带请求参数,参数位于 args ) , 不 同 于 浏 览 器 传 递 的 args),不同于浏览器传递的 args),不同于浏览器传递的 request_uri 的值,它可以通过内部重定向,或者使用 index 指令进行修改。不包括协议和主机名,例如 /foo/bar.html
附 nginx 模块
nginx 模块分类
核心模块:nginx 最基本最核心的服务,如进程管理、权限控制、日志记录;
标准 HTTP 模块:nginx 服务器的标准 HTTP 功能;
可选 HTTP 模块:处理特殊的 HTTP 请求
邮件服务模块:邮件服务
第三方模块:作为扩展,完成特殊功能
模块清单
核心模块:
ngx_core
ngx_errlog
ngx_conf
ngx_events
ngx_event_core
ngx_epll
ngx_regex
标准 HTTP 模块:
ngx_http
ngx_http_core #配置端口,URI 分析,服务器相应错误处理,别名控制 (alias) 等
ngx_http_log #自定义 access 日志
ngx_http_upstream #定义一组服务器,可以接受来自 proxy, Fastcgi,Memcache 的重定向;主要用作负载均衡
ngx_http_static
ngx_http_autoindex #自动生成目录列表
ngx_http_index #处理以/结尾的请求,如果没有找到 index 页,则看是否开启了 random_index;如开启,则用之,否则用 autoindex
ngx_http_auth_basic #基于 http 的身份认证 (auth_basic)
ngx_http_access #基于 IP 地址的访问控制 (deny,allow)
ngx_http_limit_conn #限制来自客户端的连接的响应和处理速率
ngx_http_limit_req #限制来自客户端的请求的响应和处理速率
ngx_http_geo
ngx_http_map #创建任意的键值对变量
ngx_http_split_clients
ngx_http_referer #过滤 HTTP 头中 Referer 为空的对象
ngx_http_rewrite #通过正则表达式重定向请求
ngx_http_proxy
ngx_http_fastcgi #支持 fastcgi
ngx_http_uwsgi
ngx_http_scgi
ngx_http_memcached
ngx_http_empty_gif #从内存创建一个 1×1 的透明 gif 图片,可以快速调用
ngx_http_browser #解析 http 请求头部的 User-Agent 值
ngx_http_charset #指定网页编码
ngx_http_upstream_ip_hash
ngx_http_upstream_least_conn
ngx_http_upstream_keepalive
ngx_http_write_filter
ngx_http_header_filter
ngx_http_chunked_filter
ngx_http_range_header
ngx_http_gzip_filter
ngx_http_postpone_filter
ngx_http_ssi_filter
ngx_http_charset_filter
ngx_http_userid_filter
ngx_http_headers_filter #设置 http 响应头
ngx_http_copy_filter
ngx_http_range_body_filter
ngx_http_not_modified_filter
可选 HTTP 模块:
ngx_http_addition #在响应请求的页面开始或者结尾添加文本信息
ngx_http_degradation #在低内存的情况下允许服务器返回 444 或者 204 错误
ngx_http_perl
ngx_http_flv #支持将 Flash 多媒体信息按照流文件传输,可以根据客户端指定的开始位置返回 Flash
ngx_http_geoip #支持解析基于 GeoIP 数据库的客户端请求
ngx_google_perftools
ngx_http_gzip #gzip 压缩请求的响应
ngx_http_gzip_static #搜索并使用预压缩的以.gz 为后缀的文件代替一般文件响应客户端请求
ngx_http_image_filter #支持改变 png,jpeg,gif 图片的尺寸和旋转方向
ngx_http_mp4 #支持.mp4,.m4v,.m4a 等多媒体信息按照流文件传输,常与 ngx_http_flv 一起使用
ngx_http_random_index #当收到 / 结尾的请求时,在指定目录下随机选择一个文件作为 index
ngx_http_secure_link #支持对请求链接的有效性检查
ngx_http_ssl #支持 https
ngx_http_stub_status
ngx_http_sub_module #使用指定的字符串替换响应中的信息
ngx_http_dav #支持 HTTP 和 WebDAV 协议中的 PUT/DELETE/MKCOL/COPY/MOVE 方法
ngx_http_xslt #将 XML 响应信息使用 XSLT 进行转换
邮件服务模块:
ngx_mail_core
ngx_mail_pop3
ngx_mail_imap
ngx_mail_smtp
ngx_mail_auth_http
ngx_mail_proxy
ngx_mail_ssl
第三方模块:
echo-nginx-module #支持在 nginx 配置文件中使用 echo/sleep/time/exec 等类 Shell 命令
memc-nginx-module
rds-json-nginx-module #使 nginx 支持 json 数据的处理
lua-nginx-module