worker_processes 1; CPU密集型work数为CPU核心数量,IO密集型work数为CPU数量的1.5倍或2倍
每一个server段定义一个虚拟主机,URI路径是指https://www.baidu.com/后面的路径,location只能用在server中,location中可以嵌套location
location [= | ~ | ~* | ^~]
location URI 对当前路径及子目录下的所有对象都生效(什么都不写的)
location = URI 精确匹配只对当前路径生效,如果是目录,只对目录生效,如果是文件,只对文件生效
location ~ URI 模式匹配,区分大小写,支持通配符
location ~* URI 模式匹配,不区分大小写,支持通配符
location ^~ URI 不使用正则表达式
优先级,= > ^~ > ~ ~* >什么都不写的
server {
listen 80; 监听端口,没有地址代表监听所有地址,也可指定IP加端口
server_name localhost; 主机名称,也就是网址
#charset koi8-r;
#access_log logs/host.access.log main; 访问日志
location / { URI路径
root html; URI路径在物理磁盘上的位置,此处是相对路径,表示nginx默认的页面文件路径
index index.html index.htm; 主页文件
autoindex on; 没有主页时自动索引
}
#error_page 404 /404.html; 访问不存在的页面时打开/404.html
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html; 错误页面URI路径下的50x.html
location = /50x.html { =是精确匹配
root html;
}
location / {
deny 192.168.1.1; 拒绝
allow 192.168.1.0/24; 允许
deny all; 拒绝所有
}
location / {
proxy_pass https://192.168.1.10; 反向代理至后端服务器
proxy_set_header X-Real-IP $remote_addr; 每次转发请求至后端服务器的时候都包含一个有客户端IP的首部(日志中会记录客户端IP)
}
location / {
auth_basic "显示的信息";
auth_basic_user_file htpasswd 密码文件路径
}
location /nginx_status {
stub_status on; 打开nginx状态显示
access_log off; 关闭写入访问日志
allow IP 允许访问的IP
deny IP 拒绝访问的IP
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ { 以php为结尾的
# proxy_pass https://127.0.0.1;
#}
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
}
upstream backend { 上游服务器组名称 server 192.168.1.2 weight=1 max_fails=2 fail_timeout=2; 权重=1 健康状态检查,错误次数=2次,超时时间2秒 server 192.168.1.3 weight=2; server 127.0.0.1 backup;
server { 设定两台服务器都挂了,就访问本机上的虚拟主机配置的页面,可设置一个错误页面。listen 80;
server_name localhost;
root html;
index index.html;
}
ip_hash:如果一个客户端连入后,会被保持在同一个realserver上。(会话保持)
least_conn:查看realserver的连接状况,挑最少连接数的realserver连接。
upstream backend {
ip_hash;
server 192.168.1.2 weight=1 max_fails=2 fail_timeout=2;
server 192.168.1.3 weight=1 max_fails=2 fail_timeout=2;
}
NGINX缓存
cache 共享内存:存储键和缓存对象的元数据
磁盘空间:存储数据
proxy_cache_path:缓存路径定义,只能定义在httpd段中
proxy_cache_path /nagix/cache levels=1:2:1 keys_zone=first:20m max_size=1G
levels=1:2:1 三级目录,第一级1个字符,第二级2个字符,第三级1个字符,最多三级,每级最多2个字符
keys_zone=first:20m 定义内存缓存大小用来存储键,first为名称,20m为大小
max_size=1G 定义磁盘缓存空间大小
谁要使用缓存功能,要在location中引用:
location / {
proxy_pass https://192.168.1.2;
proxy_cache first 启用缓存功能,使用定义的first
}