Nginx配置详解
Nginx的配置是在nginx.conf中进行配置的
主要由三部分组成
全局块
从配置文件开始到events块之间的内容是全局块,主要用来配置Nginx服务器整体运行的配置指令,主要包括配置运行Nginx的用户组、允许生成的worker process数,进行PID存放路径、日志存放路径和类型以及配置文件的引入
1 2 3 4 5 6 7 8 9 10 11 12 13
| #nginx的用户和用户组 #user nobody; # nginx处理并发的数量,值越大,处理并发数量越多 # 通常为cpu数量 worker_processes 1; #错误日志位置 #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #指定pid的存放文件 #pid logs/nginx.pid;
|
events块
主要是影响Nginx服务器与用户网络的连接,常用的配置包括是否开启对多worker process下的网络连接进行序列化,是否允许同时接受多个网络连接,选取那种事件驱动模型来处理连接请求,每个worker process可以同时支持的并发数
1 2 3 4 5 6
| events { # 每个worker process可以同时支持的连接数为1024 # nginx支持的最大并发数是worker_processes*worker_connections #如果是作为反向代理服务器的话,最大并发数是worker_processes*worker_connections/2,因为反向代理服务器,每个并发会建立与客户端的连接和与后端的连接,会占用两个连接 worker_connections 1024; }
|
http块
Nginx配置中修改最频繁的配置就是http块的配置
http块又分为了http全局块和server块
http全局块
主要配置的是文件的引入、MIME-TYPE定义、日志自定义、连接超时时间、单链接请求上限等
server块主要是虚拟主机的配置
又分为了server全局块和location块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| 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压缩 #gzip on; #实际的服务器列表 #upstream myserver { # server 127.0.0.1:8080; # server 127.0.0.1:8082; #}
HTTP服务器 server { #监听的端口号 listen 8080; 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; }
# deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # 禁止下载 # deny all; #} } include servers/*; }
|
location配置
匹配规则
location有多种匹配规则[=||*|^~] /url/
- =表示精确匹配,优先级最高
- ^
表示uri以某个字符串开头,即^/spring/ 可以被所有以/spring/开头的匹配到
为区分大小写的正则匹配,如果使用!则表示取反,不匹配的正则
*为不区分大小写的正则匹配,如果使用!*则表示取反,不匹配的正则
- /通用匹配,任何请求都会匹配到
静态文件路径
可以使用root或alias来指定静态资源文件路径,root可以配置在http块、server块、location块以及if块中,alias只能配置在location块中
root
使用root来表示请求的url时会进行完整的拼接,即如果请求使用的uri是/pic/index.html的话,使用root实际获取的是/data/www/web/pic/index.html
1 2 3
| location /pic/ { root /data/www/web; }
|
alias
alias会将location中配置的路径丢弃掉,即即如果请求使用的uri是/pic/index.html的话,使用alias实际获取的是/data/www/web/index.html
1 2 3
| location /pic/ { alias /data/www/web; }
|