20181103 Nginx(布尔教育)

nginx介绍

  • 对标Apache服务器
  • 目录介绍

conf 配置文件
html 网页文件
logs 日志文件
sbin 主要二进制程序

控制命令


./nginx             # 启动

nginx -t            # 测试配置文件语法是否正确

nginx -s reload     # 重新加载配置,不终止重启
nginx -s stop       # 立即停止
nginx -s quit       # 优雅停止,正在请求的仍然可以完成请求,之后停止
nginx -s reopen     # 重新打开日志

全局段配置

  • 配置nginx.conf中的worker_processes数量:CPU数 * 核数,另外考虑网卡的连接数
# 工作线程的数量
worker_processes  1;

events {
    # 每个工作线程的最大连接数
    worker_connections  1024;
}

server段配置虚拟主机

  • nginx.conf中一个server是一个虚拟主机,server_name是服务名称,location是服务所在的根目录
server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

}

日志管理

# 日志格式,其中$http_x_forwarded_for为用户的真实IP地址
#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;

URL重写

rewrite

location / {
    # 使用正则表达式匹配路径,进行URL重写
    rewrite (.*)$ /index.php/$1;
}

try_files

location / {
    try_files $uri /index.php?uri
}

反向代理

# 当匹配到图片格式时,到另一台服务器上获取
location ~ \.(jpeg|jpg|png|gif)$ {
    proxy_pass http://192.168.2.42:80;
    # 转发到另一台服务器时,携带真实的用户IP
    proxy_set_header X-Forwarded-For $remote_addr;
}

集群和负载均衡

# 配置upstream
upstream imageserver {
    server 192.168.1.204:8080 weight=1 max_fails=2 fail_timeout=30s;
    server 192.168.1.204:8081 weight=1 max_fails=2 fail_timeout=30s;
}

# 下游调用
location ~ \.(jpeg|jpg|png|gif)$ {
    proxy_pass http://imageserver;
    # 转发到另一台服务器时,携带真实的用户IP
    proxy_set_header X-Forwarded-For $remote_addr;
}

负载均衡的算法

  • 默认的负载均衡算法是设置计数器,轮流请求N台服务器
  • 可以安装第3方模式,来利用不同参数把请求均衡到不同服务器去,如基于cookie值区别用户做负载均衡(nginx sticky模块),或基于URI利用一致性哈希算法做均衡(NginxHttpUpstreamConsistentHash模块),或基于IP做负载均衡等。

参考

posted @ 2018-11-04 14:02  流星<。)#)))≦  阅读(199)  评论(0编辑  收藏  举报