1、配置文件的语法格式
先来看一个简单的 nginx 配置
# worker 进程数量worker_processes 1;events {# 每个 worker 进行可以处理的连接数量worker_connections 1024;}# http 服务http {# 可以处理的 mime 类型include mime.types;default_type application/octet-stream;# 是否可以发送文件sendfile on;# 连接超时时间keepalive_timeout 65;# server 服务模块(可以有多个)server {listen 80; # 监听的端口号server_name localhost; # 主机名# 访问 URI 路径(可以有多个)location / {root html; # 当前站点的根目录,是一个相对路径,相对于 /usr/local/nginx 根目录而言index index.html index.htm;}location /static {root html;index index.html index.htm;}location /nginx_status {stub_status on;access_log off;}}server {listen 80; # 监听的端口号# 支持通配符匹配,default 代表默认项,如果没有 default 则以最后一个 server 作为默认项server_name www.wesoft.org *.wesoft.org wesoft.* default;location / {root html;index index.html index.htm;}location /nginx_status {stub_status on;access_log off;}}}
上述配置中的 events、http、server、location、upstream 等属于配置项块。而 worker_processes 、worker_connections、include、listen 属于配置项块中的属性。 /nginx_status 属于配置块的特定参数参数。其中 server 块嵌套于 http 块,其可以直接继承访问 http 块当中的参数。
| 配置块 | 名称开头用大口号包裹其对应属性 |
|---|---|
| 属性 | 基于空格切分属性名与属性值,属性值可能有多个项 |
都以空格进行切分
如:access_log
logs/host.access.log main |
| 参数 | 其配置在 块名称与大括号间,其值如果有多个也是通过空格进行拆 |
注意:如果配置项值中包括语法符号,比如空格符,那么需要使用单引号或双引号括住配置项值,否则Nginx会报语法错误。例如:
log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';
location
语法:location [ = | ~ | ~* | ^~ | @ ] /uri/
=:表示把URI作为字符串,以便与参数中的uri做完全匹配。
/: 基于uri目录匹配
~:表示正则匹配URI时是字母大小写敏感的。
~*:表示正则匹配URI时忽略字母大小写问题。
^~:表示正则匹配URI时只需要其前半部分与uri参数匹配即可。
root
可配置在 server 与 location 中,基于 root 路径 + URL 中路径去寻找指定文件
alias
只能配置 location 中。基于 alias 路径 + URL,移除 location 前缀后的路径来寻找指定文件
2、配置第一个静态WEB服务
server {listen 80;server_name www.wesoft.org;root /usr/www/html/;location / {index index.html;}location /test {# root /usr/www/html/test/; # root 属性会将 /test 加入到路径的后面alias /usr/www/html/test/; # alias 属性不会将 /test 加入到路径的后面index index.html;}}
3、动静分离
基于目录动静分离
location /static {alias /usr/www/html/static/index index.html;}
基于正则动静分离
当使用正则匹配的时候,访问的时候不用带 static 目录
location ~* \.(gif|jpg|jpeg|png|js|css)$ {root /usr/www/html/static/}
4、防盗链配置
# 加入至指定 location 即可实现valid_referers none blocked *.wesoft.org;if ($invalid_referer) {return 403;}
如:配置静态资源防盗链
location ~* \.(jpg|jpeg|gif|png|css|js)$ {root /usr/www/html/static/;valid_referers none blocked *.wesoft.org;if ($invalid_referer) {return 403;}}
5、下载限速
location /download {limit_rate 1m; # 限制每秒下载速度,这个属性可以写在 server 中,全局生效limit_rate_after 30m; # 大小超过 30m 之后才启用限速,这个属性可以写在 server 中,全局生效}
6、创建 IP 黑名单
#封禁指定IPdeny 192.168.0.1;allow 192.168.0.1;#开放指定IP 段allow 192.168.0.0/24;#封禁所有deny all;#开放所有allow all;# 创建黑名单文件echo 'deny 192.168.0.132;' >> balck.ip#http 配置块中引入 黑名单文件include black.ip;
