nginx 配置语法
- 配置文件由四个指令块组成(http, upstream, server, location)
- 指令块内容 以 " { " 开头 " } " 结尾,表示指令块配置到此结束, 指令块中配置指令以 " ; " 结尾. 指令与参数之间以 一个或者多个空格 做分隔.
- include 可以允许组合多个配置文件, 提升可维护性
- " # " 作为注释, 跟shell 语法一样 使用 " $ " 调用变量, 并支持正则.
web服务器
server {
listen 127.0.0.1:8080 # 监听本地8080端口 不指定ip 则指监听所有ip的8080.
location / {
root /tmp/web/ # 静态网页读取地址
index index.html # index 进入 index.html
access_log /var/logs/web.log main # main为命名 与http中的log_format main中的main一致
set $limmit rate 1k # 限制反应速度
}
反向代理
http {
include xxxxx;
proxy_cache_path /tmp/nginxcache(缓存文件) levels=1:2 keys_zon=my_cache:10m(开启10m共享内存) max_size=10g inactive=60m(60分钟) use_tmp_path=off;
log_format main $remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for # 日志格式 参数部分是日志中记录的 内容, 里面这些变量是各个模块的 Embedded Variables 中的 变量 官网查看
gzip on # 此时html 都会压缩
gzip_min_length 1 # 效于1 不压缩
gzip_comp_level 2 # 压缩级别为2
gzip_types text/plain application/x-javascript #text/plain 和 application/x-javascript # 格式才压缩
gzip on/off #开启/关闭 压缩功能
gzip type # 某类型压缩
gzip_min_length 1 # 效于1 不压缩
upstream myservice {
server ip:port;
server ip:port; # 上游服务 地址和端口
}
server {
listen 127.0.0.1:8080 # 监听本地8080端口 不指定ip 则指监听所有ip的8080.
location / {
proxy_set_header HOST $host; # 设置头信息可以获取真实ip 而不是代理ip
proxy_set_header X-Real-IP $remote_addr; # 获取真实地址而不是代理
proxy_cache my_cache; # 开启缓存,同时http模块中要打开
proxy_set_header # 设置http头信息
proxy_cache_key $host$url$is_args$args; # 设置 cache 的key
proxy_cache_valid 200 304 302 1d; # 允许使用cache的情况 200 304 302 cache有效期1天
proxy_pass http://myservice # 只有 上面定义的上游服务可以 连接
access_log /var/logs/web.log main # main为命名 与http中的log_format main中的main一致
set $limmit rate 1k # 限制反应速度
}
} # 当使用nginx 容器做 web服务器时 可只设置 server 模块
}