Nginx配置文件的基本结构
Nginx配置文件由一组指令(directives)组成,指令分为简单指令和块指令。
-
简单指令 simple directives
简单的指令格式为:
<指令名> <参数>;
-
块指令block directives(上下文 context)
块指令格式为:
<指令名> ...{ # 简单指令 # 块指令 }
将Nginx配置为反向代理服务器需要的块指令有events, http, server, location, 其他的块指令还有作为负载均衡时用的upstream,作为邮件服务器时用的mail等,块指令内可以嵌套其他简单指令和块指令。另外,文件的最外层被成为main context。
-
文件基本结构
举个例子,这是一个Nginx配置文件的基本结构
nginx.conf
user nobody; worker process 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { ... } # some comments http { ... server { # server1 location ... { # location 1 ... } location ... { # location 2 ... } } server { # server 2 ... } }
示例文件的最开始是4个简单指令
- user指定了Nginx工作进程运行时使用的用户和组。语法为
user username [groupname]
当groupname省略时与username相同,默认为user nobody nobody
。 - worker process指定了工作进程的个数。
- error log指定了存放错误日志的文件。语法为
error_log file [level]
,level可选debug,info,notice,warn,error,crit,alert,emerg,默认为error。 - pid指定了存放主进程id的文件。
接下来是events块指令,用来配置网络连接相关的的参数。比如最大连接数,事件驱动模型等等。
- user指定了Nginx工作进程运行时使用的用户和组。语法为
静态内容服务器
-
请求匹配
server { location / { root /data/www; } location /images/ { root /data; } }
Nginx会根据不同的请求路径,将请求匹配到不同的location,比如/可以匹配任何路径,
/images/
可以匹配任何以/images/
开头的路径。当有多个location匹配时,Nginx选择最长前缀对应的location来处理请求。比如以下urlhttps://localhost/images/example.png
匹配到
/images/
而不是/
,最终被映射为文件/data/images/example.png
。
反向代理服务器
server {
location / {
proxy_pass https://localhost:8080;
}
location /images/ {
root /data;
}
}
proxy_pass
是ngx_http_proxy_module
模块中的指令,用于转发请求。模块中的其他指令可以查官方文档。
负载均衡
http {
upstream myapp1 {
server srv1.example.com weight=3;
server srv2.example.com;
server srv3.example.com;
}
server {
listen 80;
location / {
proxy_pass https://localhost:8080;
}
}
}
配置文件生成工具
配置文件的指令非常多,要全部记住是很困难的,网上有一些自动生成配置文件的工具,可以通过图新界面配置一些基本的功能,生成基本的配置文件,再根据需要自己修改。这里列出几个在线生成工具: