Nginx 配置文件详解

1,493 阅读4分钟

Nginx 配置详解

1. Nginx 基本操作

# /usr/local/webserver/nginx 为安装位置
# 查看版本
/usr/local/webserver/nginx/sbin/nginx -v
# 创建 Nginx 运行使用的用户 www:
/usr/sbin/groupadd www 
/usr/sbin/useradd -g www www
# 其他操作
/usr/local/webserver/nginx/sbin/nginx -s reload            # 重新载入配置文件
/usr/local/webserver/nginx/sbin/nginx -s reopen            # 重启 Nginx
/usr/local/webserver/nginx/sbin/nginx -s stop              # 停止 Nginx

2. Nginx 配置文件

# 三部分组成 1.全局块 2.events块 3.http块

# 1.全局块
#user  nobody;
user www www;        # 用户
worker_processes  2; # 并发处理的值 值越大处理并发越多 设置值和CPU核心数一致

#error_log  logs/error.log;
error_log /usr/local/webserver/nginx/logs/nginx_error.log crit; #日志位置和日志级别
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;
pid /usr/local/webserver/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;

# 2.events块 主要影响 Nginx 与 用户 的网络连接
events {
    use epoll;
    worker_connections  1024;  # 支持最大连接数 配置频繁
}

# 3.http块
http {
	# 3.1 http 全局块 minme.type、日志自定义、超时时间
    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';
    #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;
    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 8m;

    sendfile        on;
    #tcp_nopush     on;
    tcp_nopush on;
    keepalive_timeout 60;
    tcp_nodelay on;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;

    #keepalive_timeout  0;
    #keepalive_timeout  65;

    #gzip  on;
    #limit_zone crawler $binary_remote_addr 10m;
    
    # 3.2 http server 块
    # 下面是server虚拟主机的配置 使用主要在server配
    server {
        listen       9090; #监听端口
        server_name  localhost; #域名

        index index.html index.htm index.php index.jsp; 
        root /usr/local/webserver/nginx/html; #站点目录

        #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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #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;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
        access_log off;
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

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

}

# 测试配置文件正确性
[root@master conf]# /usr/local/webserver/nginx/sbin/nginx -t
# 启动
[root@master conf]# /usr/local/webserver/nginx/sbin/nginx
访问 IP 

3. Nginx 配置反向代理

# 输入地址跳转 Tomcat 主页
# 实现
# 1.准备工作 安装Tomcat 启动Tomcat ./startup.sh 
# 2.配置反向代理

 # 普通反向代理
 server {
 	location / {
            root   html;
            proxy_pass http://内网IP:8080; # 反向代理
            index  index.html index.htm;
        }
 }
 # 通过路径决定访问哪个服务器
 server {
         listen       9001;
         server_name  内网IP;

         location /MS01/ {
             proxy_pass http://172.26.245.104:8080;
         }
         location /MS02/ {
             proxy_pass http://172.26.245.104:8090;
         }

  }

4. Nginx 配置负载均衡

# 负载均衡的方式 :
# 1.轮询 (默认)
# 2.weight 权重 可以 在服务后加上 weight = 10;
# 3.ip_hash 在自定义服务方式加入 ip_hash 让同一个用户只能访问同一台服务器 解决session共享问题
# 4.fair(第三方) 在自定义服务方式加入 fair  按后端服务器的响应时间进行分配

# 配置写在 http{} 中
upstream myserver {
    server 172.26.245.104:8080;
    server 172.26.245.104:8090;
}
server {
        listen       9090; #监听端口
        server_name  172.26.245.104; #域名

        index index.html index.htm index.php;
        root /usr/local/webserver/nginx/html; #站点目录
        location / {
            root   html;
            proxy_pass http://myserver;  # 设置自定义的请求方式
            index  index.html index.htm;
        }
}

5. Nginx 配置动静分离

# 动静分离
# 静态请求请求静态资源服务器(html\css\js\image ..),动态请求请求Tomcat
# 准备工作:在/data/下放入静态资源
# 通过 location / 进行静态抽离
location /www/ {
            root   /data/;
            index  index.html index.htm;
}
location /image/ {
            root   /data/;
            autoindex on;
}

6. Nginx 高可用

# 如果 Nginx 宕机 请求无法实现
# 一台 master 一台 backup  
# 做主备配置  1.两台Nginx 2.keepalived 3.虚拟IP
# 配置两台服务器 安装 Nginx
# 安装 yum install keepalived -y
# 检查 rpm -q -a keepalived
# 修改 etc/keepalived/keepalived.conf
! Configuration File for keepalived
# 全局
global_defs {      # 全局定义
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL # 主机名 内网IP
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_script chk_http_port {  # 检测脚本

	script "/usr/local/src/nginx_check.sh" # 脚本成立 
	
	interval 2 # 检测脚本执行间隔
	
	weight 2 # 权重

}

vrrp_instance VI_1 {
    state MASTER  # 备份服务器上将MASTER 改为BACKUP
    interface eth0 # 网卡
    virtual_router_id 51 # 主、备机virtual_router_id 必须相同
    priority 100 # 主、备机取不同优先级,主机值较大,备机值较小  主100 从90
    advert_int 1 # 心跳
    authentication {  # 校验方式
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.200.16  # VRRP H虚拟地址
        # 192.168.200.17
        # 192.168.200.18
    }
}
# 检测脚本 /usr/local/src/nginx_check.sh
# !/bin/bash
A=`ps -C nginx -no-header |wc -l`
if [ $A -eq 0 ];then
	/usr/local/nginx/sbin/nginx # 启动nginx
	sleep 2
	if [`ps -C nginx --no-header |wc -l` -eq 0 ];then # 主服务器挂掉
		killall keepalived
	fi
fi

# 把两台Nginx 和 keepalived 启动
启动nginx : ./nginx
启动keepalived : systemctl start keepalived.service

Nginx 原理

nginx原理

优点

  1. 可以利用 nginx -s reload 热部署,利用nginx 进行热部署操作
  2. 每个 worker 都是独立进程,降低服务器风险

问题

  1. 设置多少个 worker 合适 ? 几核cpu设置 几个 worker

  2. 连接数worker_connection ? 发送请求 静态资源 占用了worker 两个 动态资源占用worker 四个 连接数

  3. 支持最大并发数 ? 一个master 四个worker 每个最大1024 41024/2 或者 41024/4