nginx简介及基本操作

一、Nginx介绍

1)Nginx是什么

Nginx 是一个开源且高性能、可靠的 Http Web 服务、代理服务。

2)为什么选择Nginx服务

1)Nginx 技术成熟,具备的功能是企业最常使用而且最需要的;
2)适合当前主流架构趋势, 微服务、云架构、中间层;
3)统一技术栈, 降低维护成本, 降低技术更新成本;

3)Nginx重要特性

Nginx 采用 Epool 网络模型, Apache 采用 Select 模型;

  • Select: 当用户发起一次请求, select 模型就会进行一次遍历扫描,从而导致性能低下;
  • Epool: 当用户发起请求, epool 模型会直接进行处理,效率高效,并无连接限制;

二、Nginx安装部署

Nginx的安装主要分为以下几种:
1)源码编译(1.版本随意 2.安装复杂 3.升级繁琐);
2)epel仓库(1.版本较低 2.安装简单 3.配置不易读);
3)官方仓库(1.版本较新 2.安装简单 3.配置易读,推荐);

1)源码编译安装

① 创建运行Nginx服务的用户

[root@nginx ~]# groupadd www -g 888
[root@nginx ~]# useradd www -s /sbin/nologin -M -u 888 -g 888
[root@nginx ~]# id www
uid=888(www) gid=888(www) 组=888(www)

② 安装所需依赖

[root@nginx ~]# yum -y install openssl-devel pcre-devel 

③ 获取软件包

[root@nginx ~]# mkdir -p /data/soft
[root@nginx ~]# cd /data/soft/
[root@nginx soft]# wget http://nginx.org/download/nginx-1.16.1.tar.gz

④ 编译安装

[root@nginx soft]# tar zxf nginx-1.16.1.tar.gz 
[root@nginx soft]# cd nginx-1.16.1/
[root@nginx nginx-1.16.1]# ./configure --user=www --group=www --prefix=/opt/nginx-1.16.0/ --with-http_stub_status_module --with-http_ssl_module --with-pcre && make && make install

⑤ 创建软连接

[root@nginx nginx-1.16.1]# ln -s /opt/nginx-1.16.0/ /opt/nginx
[root@nginx nginx-1.16.1]# ls -lh /opt
总用量 0
lrwxrwxrwx  1 root root 18 3月  30 09:06 nginx -> /opt/nginx-1.16.0/
drwxr-xr-x  6 root root 54 3月  30 09:05 nginx-1.16.0

⑥ 启动nginx

[root@nginx nginx]# /opt/nginx/sbin/nginx -t
[root@nginx nginx]# /opt/nginx/sbin/nginx 
[root@nginx nginx]# ss -lnt | grep 80
LISTEN     0      128          *:80                       *:*                  
[root@nginx nginx]# curl 127.0.0.1

2)YUM安装

① 配置官方yum源

[root@nginx ~]# vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key

② 安装nginx

[root@nginx ~]# yum -y install nginx

③ 启动服务并测试

[root@nginx ~]# nginx -t
[root@nginx ~]# systemctl start nginx && systemctl enable nginx

三、Nginx配置文件说明

1)查看配置文件

[root@nginx ~]# rpm -ql nginx
...................................................                     
/etc/logrotate.d/nginx                     #nginx日志切割的配置文件
/etc/nginx/nginx.conf                      #nginx主配置文件 
/etc/nginx/conf.d                          #子配置文件
/etc/nginx/conf.d/default.conf             #默认展示的页面一样 
/etc/nginx/mime.types                      #媒体类型 (http协议中的文件类型)
/etc/sysconfig/nginx                       #systemctl 管理 nginx的使用的文件
/usr/lib/systemd/system/nginx.service      #systemctl 管理nginx(开 关 重启 reload)配置文件       
/usr/sbin/nginx                            #nginx命令
/usr/share/nginx/html                      #站点目录 网站的根目录 
/var/log/nginx                             #nginx日志 access.log 访问日志
...................................................                     

2)查看已经编译的模块

[root@nginx ~]# nginx -V

3)配置文件注解

Nginx 主配置文件/etc/nginx/nginx.conf 是一个纯文本类型的文件,整个配置文件是以区块的形式组织的。一般,每个区块以一对大括号{}来表示开始与结束。
Nginx 主配置文件整体分为三块进行学习,分别是

  • CoreModule(核心模块)
  • EventModule(事件驱动模块)
  • HttpCoreModule(http 内核模块)

① 配置文件主区域配置

user  nginx;                    #定义运行nginx进程的用户
worker_processes  1;            #Nginx运行的work进程数量(建议与CPU数量一致或 auto)

error_log  /var/log/nginx/error.log warn;             #nginx错误日志
pid        /var/run/nginx.pid;                        #nginx运行pid

② 配置文件事件区域

events {
    worker_connections  1024;  #每个 worker 进程支持的最大连接数
}

③ 配置http区域

http {
    include       /etc/nginx/mime.types;          #Nginx支持的媒体类型库文件
    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"';

    access_log  /var/log/nginx/access.log  main;    #访问日志保存路径

    sendfile        on;                             #开启高效传输模式
    #tcp_nopush     on;                       
    keepalive_timeout  65;                          #连接超时时间
    #gzip  on;                                      #开启压缩
    include /etc/nginx/conf.d/*.conf;               #包含子配置文件
}    

④ 子配置文件内容

[root@nginx ~]# egrep -v "#|^$" /etc/nginx/conf.d/default.conf
server {
    listen       80;             #指定监听端口
    server_name  localhost;      #指定监听的域名
    location / {              
        root   /usr/share/nginx/html;     #定义站点的目录
        index  index.html index.htm;      #定义首页文件
    }
    error_page   500 502 503 504  /50x.html;    #优雅显示页面信息
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
  • http server location 扩展了解项;
  • http{}层下允许有多个 Server{}层,一个 Server{}层下又允许有多个 Location;
  • http{} 标签主要用来解决用户的请求与响应;
  • server{} 标签主要用来响应具体的某一个网站;
  • location{} 标签主要用于匹配网站具体 URL 路径;

四、Nginx虚拟主机配置实战

1)基于域名的虚拟主机

[root@nginx ~]# cat /etc/nginx/nginx.conf    

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    #include /etc/nginx/conf.d/*.conf;
    server   {
        listen       80;
        server_name  www.lzj.com;
        location / {
            root   /usr/share/nginx/html/www;
            index  index.html index.htm;
        }
    }
    server   {
        listen       80;
        server_name  blog.lzj.com;
        location / {
            root   /usr/share/nginx/html/blog;
            index  index.html index.htm;
        }
    }
}

2)基于端口的虚拟主机

端口号优先级比域名要高!

[root@nginx ~]# cat /etc/nginx/nginx.conf    

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    #include /etc/nginx/conf.d/*.conf;
    server   {
        listen       81;
        server_name  www.lzj.com;
        location / {
            root   /usr/share/nginx/html/www;
            index  index.html index.htm;
        }
    }
    server   {
        listen       82;
        server_name  blog.lzj.com;
        location / {
            root   /usr/share/nginx/html/blog;
            index  index.html index.htm;
        }
    }
}

3)基于IP的虚拟主机

添加第二IP:

ip addr add 192.168.1.100/24 dev ens33

配置文件:

[root@nginx ~]# cat /etc/nginx/nginx.conf    

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    #include /etc/nginx/conf.d/*.conf;
    server   {
        listen       192.168.1.7:81;
        server_name  www.lzj.com;
        location / {
            root   /usr/share/nginx/html/www;
            index  index.html index.htm;
        }
    }
    server   {
        listen       192.168.1.100:82;
        server_name  blog.lzj.com;
        location / {
            root   /usr/share/nginx/html/blog;
            index  index.html index.htm;
        }
    }
}

五、Nginx虚拟主机配置优化

所有配置都写入一个配置文件维护起来比较麻烦,如果修改错了,影响所有的页面,所以我们应该拆分nginx的配置文件为各个子配置!

1)Nginx主配置文件

[root@nginx /etc/nginx/conf.d]# cat /etc/nginx/nginx.conf 

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

2)子配置文件www

[root@nginx /etc/nginx/conf.d]# cat /etc/nginx/conf.d/01-www.conf 
server   {
    listen       80;
    server_name  www.lzj.com;
    location / {
        root   /usr/share/nginx/html/www;
        index  index.html index.htm;
    }
}

3)子配置文件blog

[root@nginx /etc/nginx/conf.d]# cat /etc/nginx/conf.d/02-blog.conf 
server   {
    listen       80;
    server_name  blog.lzj.com;
    location / {
        root   /usr/share/nginx/html/blog;
        index  index.html index.htm;
    }
}

4)创建代码目录及首页

[root@nginx /etc/nginx/conf.d]# mkdir /usr/share/nginx/html/{www,blog}
[root@nginx /etc/nginx/conf.d]# echo "www" > /usr/share/nginx/html/www/index.html
[root@nginx /etc/nginx/conf.d]# echo "blog" > /usr/share/nginx/html/blog/index.html 

5)访问测试

[root@nginx ~]# nginx -t
[root@nginx ~]# tail -1 /etc/hosts  
192.168.1.7 www.lzj.com blog.lzj.com
[root@nginx ~]# curl www.lzj.com
www
[root@nginx ~]# curl blog.lzj.com
blog

六、Nginx日志

$remote_addr # 记录客户端 IP 地址
$remote_user # 记录客户端用户名
$time_local # 记录通用的本地时间
$time_iso8601 # 记录 ISO8601 标准格式下的本地时间
$request # 记录请求的方法以及请求的 http 协议
$status # 记录请求状态码(用于定位错误信息)
$body_bytes_sent # 发送给客户端的资源字节数,不包括响应头的大小
$bytes_sent # 发送给客户端的总字节数
$msec # 日志写入时间。单位为秒,精度是毫秒
$http_referer # 记录从哪个页面链接访问过来的
$http_user_agent # 记录客户端浏览器相关信息
$http_x_forwarded_for #记录客户端 IP 地址
$request_length # 请求的长度(包括请求行, 请求头和请求正文)
$request_time # 请求花费的时间,单位为秒,精度毫秒
# 注:如果 Nginx 位于负载均衡器, nginx 反向代理之后, web 服务器无法直接获取到客 户端真实的 IP 地址
# $remote_addr 获取的是反向代理的 IP 地址。 反向代理服务器在转发请求的 http 头信息中
# 增加 X-Forwarded-For 信息,用来记录客户端 IP 地址和客户端请求的服务器地址

七、Nginx注意事项

1)如果是yum安装,启动关闭命令推荐使用systemctl。不要混着nginx -s这样用;
2)相同域名相同端口会报冲突,比如都是0.0.0.0:80;
3)没有首页会报403而不是404;
4)端口优先级高于域名;
5)ip+端口的优先级是最高的;
6)所有域名都匹配不上的时候,默认转发到根据ASCII码排序优先的配置文件;

八、Nginx默认的日志切割文件

[root@nginx ~]# cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
        daily
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 nginx adm
        sharedscripts
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}

九、自定义Nginx日志切割脚本

/usr/bin/env bash

set -e      #如果脚本中出现错误,则立即停止
LOG_PATH="/var/gb/logs/"     # 定义nginx 日志路径
ACCESS_LOG="access.log"
ERROR_LOG="error.log"      # 定义nginx 访问日志文件名称

for i in `find  $LOG_PATH -name "$ACCESS_LOG"`; do
    cd $(dirname $i)
    # 切割access日志
    if [[ -f $ACCESS_LOG ]]; then
        cp {,$(date +%F)-}${ACCESS_LOG}
        : > $ACCESS_LOG
    fi
    
    # 如果error日志>20m,切
    if [[ -f $ERROR_LOG ]]; then
        ERROR_SIZE=`ls -l $ERROR_LOG | awk '{ print $5 }'`
        if [[ $ERROR_SIZE -gt 20971520 ]]; then
            cp {,$(date +%F)-}${ERROR_LOG}
            : > ${ERROR_LOG}
        fi
    fi
done

# 查找nginx 日志目录下7天前的日志并删除
find ${LOG_PATH} -type f -name "*-${ACCESS_LOG}" -mtime +7 -delete
find ${LOG_PATH} -type f -name "*-${ERROR_LOG}"  -mtime +7 -delete
*************** 当你发现自己的才华撑不起野心时,就请安静下来学习吧!***************
原文地址:https://www.cnblogs.com/lvzhenjiang/p/14021972.html