典型配置
# main段配置信息user nginx; # 运行用户,默认即是nginx,可以不进行设置worker_processes auto; # Nginx 进程数,一般设置为和 CPU 核数一样error_log /var/log/nginx/error.log warn; # Nginx 的错误日志存放目录pid /var/run/nginx.pid; # Nginx 服务启动时的 pid 存放位置# events段配置信息events {use epoll; # 使用epoll的I/O模型(如果你不知道Nginx该使用哪种轮询方法,会自动选择一个最适合你操作系统的)worker_connections 1024; # 每个进程允许最大并发数}# http段配置信息# 配置使用最频繁的部分,代理、缓存、日志定义等绝大多数功能和第三方模块的配置都在这里设置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; # Nginx访问日志存放位置sendfile on; # 开启高效传输模式tcp_nopush on; # 减少网络报文段的数量tcp_nodelay on;keepalive_timeout 65; # 保持连接的时间,也叫超时时间,单位秒types_hash_max_size 2048;include /etc/nginx/mime.types; # 文件扩展名与类型映射表default_type application/octet-stream; # 默认文件类型include /etc/nginx/conf.d/*.conf; # 加载子配置项}# server段配置信息server {listen 80; # 配置监听的端口server_name localhost; # 配置的域名# location段配置信息location / {root /usr/share/nginx/html; # 网站根目录index index.html index.htm; # 默认首页文件deny 172.168.22.11; # 禁止访问的ip地址,可以为allallow 172.168.33.44;# 允许访问的ip地址,可以为all}error_page 500 502 503 504 /50x.html; # 默认50x对应的访问页面error_page 400 404 error.html; # 同上}stream {#nginx代理172.18.103.197:8899服务upstream backend {server 172.18.103.197:8899 weight=1;}server {listen 9001;proxy_pass backend;}#nginx代理172.18.103.197:8489服务server {listen 8489;proxy_pass 172.18.103.197:8489;}server {listen 8848;proxy_pass 172.18.103.197:8848;}}
- main:全局配置,对全局生效; - events:配置影响 Nginx 服务器与用户的网络连接; - http:配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置; - server:配置虚拟主机的相关参数,一个 http 块中可以有多个 server 块; - location:用于配置匹配的 uri ; - upstream:配置后端服务器具体地址,负载均衡配置不可或缺的部分。 |
![]() |
|---|---|
main段配置
#user USERNAME [GROUP] #运行用户名 用户组可选user nginx; # 运行用户,默认即是nginx,可以不进行设置pid /var/run/nginx.pid; # Nginx 服务启动时的 pid 存放位置worker_rlimit_nofile 20480; # 可以理解成每个worker子进程的最大连接数量。worker_rlimit_core 50M; # 存放大小限制working_directory /opt/nginx/tmp; # 存放目录worker_processes auto; # Nginx 进程数,一般设置为和 CPU 核数一样error_log /var/log/nginx/error.log warn; # Nginx 的错误日志存放目录worker_priority -10; # 120-10=110,110就是最终的优先级worker_shutdown_timeout 5s;timer_resolution 100ms;daemon off; # 默认是on,后台运行模式
user:指定运行 Nginx 的 woker 子进程的属主和属组,其中组可以不指定。
pid:指定运行 Nginx master 主进程的 pid 文件存放路径。
worker_rlimit_nofile_number:指定 worker 子进程可以打开的最大文件句柄数。
worker_rlimit_core:指定 worker 子进程异常终止后的 core 文件,用于记录分析问题。
worker_processes_number:指定 Nginx 启动的 worker 子进程数量。
worker_cpu_affinity:将每个 worker 子进程与我们的 cpu 物理核心绑定。将每个 worker 子进程与特定 CPU 物理核心绑定,优势在于,避免同一个 worker 子进程在不同的 CPU 核心上切换,缓存失效,降低性能。但其并不能真正的避免进程切换
worker_priority:指定 worker 子进程的 nice 值,以调整运行 Nginx 的优先级,通常设定为负值,以优先调用 Nginx 。(Linux 默认进程的优先级值是120,值越小越优先;nice 定范围为 -20 到 +19 )应用的默认优先级值是120加上 nice 值等于它最终的值,这个值越小,优先级越高。
worker_shutdown_timeout:指定 worker 子进程优雅退出时的超时时间。
timer_resolution:worker 子进程内部使用的计时器精度,调整时间间隔越大,系统调用越少,有利于性能提升;反之,系统调用越多,性能下降。
daemon:指定 Nginx 的运行方式,前台还是后台,前台用于调试,后台用于生产。
events端配置
use
Nginx 使用何种事件驱动模型。
use method; # 不推荐配置它,让nginx自己选择method 可选值为:select、poll、kqueue、epoll、/dev/poll、eventport
worker_connections
worker 子进程能够处理的最大并发连接数。
worker_connections 1024 # 每个子进程的最大连接数为1024
accept_mutex
是否打开负载均衡互斥锁。
accept_mutex on # 默认是off关闭的,这里推荐打开
server_name 指令
指定虚拟主机域名。
server_name name1 name2 name3# 示例:server_name www.nginx.com;
域名匹配的四种写法:
- 精确匹配:server_name www.nginx.com ;
- 左侧通配:server_name *.nginx.com ;
- 右侧统配:server_name www.nginx.* ;
- 正则匹配:server_name ~^www.nginx.*$ ;
匹配优先级:精确匹配 > 左侧通配符匹配 > 右侧通配符匹配 > 正则表达式匹配。
server_name 配置实例
1) 配置本地 DNS 解析 vim /etc/hosts
# 添加如下内容,其中 121.42.11.34 是阿里云服务器IP地址121.42.11.34 www.nginx-test.com121.42.11.34 mail.nginx-test.com121.42.11.34 www.nginx-test.org121.42.11.34 doc.nginx-test.com121.42.11.34 www.nginx-test.cn121.42.11.34 fe.nginx-test.club
[注意] 这里使用的是虚拟域名进行测试,因此需要配置本地 DNS 解析,如果使用阿里云上购买的域名,则需要在阿里云上设置好域名解析。
2) 配置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;}}
3) 访问分析
- 当访问 www.nginx-test.com 时,都可以被匹配上,因此选择优先级最高的“完全匹配”;
- 当访问 mail.nginx-test.com 时,会进行“左匹配”;
- 当访问 www.nginx-test.org 时,会进行“右匹配”;
- 当访问 doc.nginx-test.com 时,会进行“左匹配”;
- 当访问 www.nginx-test.cn 时,会进行“右匹配”;
- 当访问 fe.nginx-test.club 时,会进行“正则匹配”。
root
指定静态资源目录位置,它可以写在 http 、 server 、 location 等配置中。 ```java root path
例如: location /image { root /opt/nginx/static; }
当用户访问 www.test.com/image/1.png 时,实际在服务器找的路径是 /opt/nginx/static/image/1.png
[注意] root 会将定义路径与 URI 叠加, alias 则只取定义路径。<a name="HIBib"></a>## alias指定静态资源目录位置,它**只能写在 location** 中。```javalocation /image {alias /opt/nginx/static/image/;}当用户访问 www.test.com/image/1.png 时,实际在服务器找的路径是 /opt/nginx/static/image/1.png
[注意] 使用 alias 末尾一定要添加 / ,并且它只能位于 location 中。
location
配置路径。
location [ = | ~ | ~* | ^~ ] uri { …}
匹配规则:
- = 精确匹配;
- ~ 正则匹配,区分大小写;
- ~* 正则匹配,不区分大小写;
- ^~ 匹配到即停止搜索;
匹配优先级:= > ^~ > ~ > ~* > 不带任何字符。
配置实例
server {listen 80;server_name www.nginx-test.com;# 只有当访问 www.nginx-test.com/match_all/ 时才会匹配到/usr/share/nginx/html/match_all/index.htmllocation = /match_all/ {root /usr/share/nginx/htmlindex index.html}# 当访问 www.nginx-test.com/1.jpg 等路径时会去 /usr/share/nginx/images/1.jpg 找对应的资源location ~ \.(jpeg|jpg|png|svg)$ {root /usr/share/nginx/images;}# 当访问 www.nginx-test.com/bbs/ 时会匹配上 /usr/share/nginx/html/bbs/index.htmllocation ^~ /bbs/ {root /usr/share/nginx/html;index index.html index.htm;}}
1) location 中的反斜线
location /test {...}location /test/ {...}
- 不带 / 当访问 www.nginx-test.com/test 时, Nginx 先找是否有 test 目录,如果有则找 test 目录下的 index.html ;如果没有 test 目录, nginx 则会找是否有 test 文件;
- 带 / 当访问 www.nginx-test.com/test 时, Nginx 先找是否有 test 目录,如果有则找 test 目录下的 index.html ,如果没有它也不会去找是否存在 test 文件。
2) return
停止处理请求,直接返回响应码或重定向到其他 URL ;执行 return 指令后, location 中后续指令将不会被执行。 ```java
return code [text]; return code URL; return URL;
例如: location / { return 404; # 直接返回状态码 }
location / { return 404 “pages not found”; # 返回状态码 + 一段文本 }
location / { return 302 /bbs ; # 返回状态码 + 重定向地址 }
location / { return https://www.baidu.com ; # 返回重定向地址 }
<a name="ql9pU"></a>## rewrite根据指定正则表达式匹配规则,重写 URL 。<br />语法:rewrite 正则表达式 要替换的内容 [flag];<br />上下文:server、location、if<br />示例:rewirte /images/(.*\.jpg)$ /pic/$1; _# $1是前面括号(.*\.jpg)的反向引用_flag 可选值的含义:- last 重写后的 URL 发起新请求,再次进入 server 段,重试 location 的中的匹配;- break 直接使用重写后的 URL ,不再匹配其它 location 中语句;- redirect 返回 302 临时重定向;- permanent 返回 301 永久重定向。```javaserver{listen 80;server_name fe.lion.club; # 要在本地hosts文件进行配置root html;location /search {rewrite ^/(.*) https://www.baidu.com redirect;}location /images {rewrite /images/(.*) /pics/$1;}location /pics {rewrite /pics/(.*) /photos/$1;}location /photos {}}
按照这个配置我们来分析:
- 当访问 fe.lion.club/search 时,会自动帮我们重定向到 https://www.baidu.com;
- 当访问 fe.lion.club/images/1.jpg 时,第一步重写 URL 为 fe.lion.club/pics/1.jpg ,找到 pics 的 location ,继续重写 URL 为 fe.lion.club/photos/1.jpg ,找到 /photos 的 location 后,去 html/photos 目录下寻找 1.jpg 静态资源。
if 指令
```java
语法:if (condition) {…}
上下文:server、location
示例: if($http_user_agent ~ Chrome){ rewrite /(.*)/browser/$1 break; }
condition 判断条件:- **$variable** 仅为变量时,值为空或以0开头字符串都会被当做 false 处理;- **=** 或 **!=** 相等或不等;- **~** 正则匹配;- **! ~** 非正则匹配;- **~*** 正则匹配,不区分大小写;- **-f** 或 **! -f** 检测文件存在或不存在;- **-d **或 **! -d** 检测目录存在或不存在;- **-e** 或 **! -e** 检测文件、目录、符号链接等存在或不存在;- **-x** 或 **! -x** 检测文件可以执行或不可执行;实例:```javaserver {listen 8080;server_name localhost;root html;location / {if ( $uri = "/images/" ){rewrite (.*) /pics/ break;}}}
当访问 localhost:8080/images/ 时,会进入 if 判断里面执行 rewrite 命令。
autoindex
用户请求以 / 结尾时,列出目录结构,可以用于快速搭建静态资源下载网站。
autoindex.conf 配置信息:
server {listen 80;server_name fe.lion-test.club;location /download/ {root /opt/source;autoindex on; # 打开 autoindex,,可选参数有 on | offautoindex_exact_size on; # 修改为off,以KB、MB、GB显示文件大小,默认为on,以bytes显示出⽂件的确切⼤⼩autoindex_format html; # 以html的方式进行格式化,可选参数有 html | json | xmlautoindex_localtime off; # 显示的⽂件时间为⽂件的服务器时间。默认为off,显示的⽂件时间为GMT时间}}
当访问 fe.lion.com/download/ 时,会把服务器 /opt/source/download/ 路径下的文件展示出来,如下图所示:
变量
Nginx 提供给使用者的变量非常多,但是终究是一个完整的请求过程所产生数据, Nginx 将这些数据以变量的形式提供给使用者。
server{listen 8081;server_name var.lion-test.club;root /usr/share/nginx/html;location / {return 200 "remote_addr: $remote_addrremote_port: $remote_portserver_addr: $server_addrserver_port: $server_portserver_protocol: $server_protocolbinary_remote_addr: $binary_remote_addrconnection: $connectionuri: $urirequest_uri: $request_urischeme: $schemerequest_method: $request_methodrequest_length: $request_lengthargs: $argsarg_pid: $arg_pidis_args: $is_argsquery_string: $query_stringhost: $hosthttp_user_agent: $http_user_agenthttp_referer: $http_refererhttp_via: $http_viarequest_time: $request_timehttps: $httpsrequest_filename: $request_filenamedocument_root: $document_root";}}
当我们访问 http://var.lion-test.club:8081/test?pid=121414&cid=sadasd 时,由于 Nginx 中写了 return 方法,因此 chrome 浏览器会默认为我们下载一个文件,下面展示的就是下载的文件内容:
remote_addr: 27.16.220.84remote_port: 56838server_addr: 172.17.0.2server_port: 8081server_protocol: HTTP/1.1binary_remote_addr: 茉connection: 126uri: /test/request_uri: /test/?pid=121414&cid=sadasdscheme: httprequest_method: GETrequest_length: 518args: pid=121414&cid=sadasdarg_pid: 121414is_args: ?query_string: pid=121414&cid=sadasdhost: var.lion-test.clubhttp_user_agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36http_referer:http_via:request_time: 0.000https:request_filename: /usr/share/nginx/html/test/document_root: /usr/share/nginx/html

