nginx基础知识

简介

  • nginx是主流的web服务器
  • LNMP是创业公司的主要架构
  • nginx的官网: http://nginx.org

源码编译安装nginx

  • 环境:centos7
  • 关闭selinux,firewalld
[root@centos7-node8 ~]# sed -i 's#SELINUX=enforcing#SELINUX=disabled#g'  /etc/selinux/config 
[root@centos7-node8 ~]# systemctl stop firewalld && systemctl disable firewalld && reboot -f
  • 下载地址:http://nginx.org/download/nginx-1.18.0.tar.gz
  • 安装
[root@centos7-node8 ~]# yum -y install gcc make pcre-devel pcre zlib openssl openssl-devel zlib-devel tree
[root@centos7-node8 ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
[root@centos7-node8 ~]# mkdir /data/applications -p
[root@centos7-node8 ~]# tar xf nginx-1.18.0.tar.gz && cd  nginx-1.18.0
[root@centos7-node8 nginx-1.18.0]# ./configure --prefix=/data/applications/nginx --with-http_ssl_module --with-http_stub_status_module --with-stream
[root@centos7-node8 nginx-1.18.0]# make && make install
[root@centos7-node8 nginx-1.18.0]# /data/applications/nginx/sbin/nginx -V   # 查看版本
  • 配置
[root@centos7-node8 ~]#  vim /etc/profile 
export NGINX_HOME="/data/applications/nginx"
export PATH=$PATH:$NGINX_HOME/sbin
[root@centos7-node8 ~]# source /etc/profile
  • 服务管理
[root@centos7-node8 ~]# nginx   #启动nginx
[root@centos7-node8 ~]# nginx -t   #测试配置
[root@centos7-node8 ~]# nginx -s reload  #重载配置
[root@centos7-node8 ~]# nginx -s stop     #关闭nginx
[root@centos7-node8 ~]# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/data/applications/nginx/sbin/nginx
[Install]
WantedBy=multi-user.target
[root@centos7-node8 ~]# systemctl start nginx    #启动nginx
[root@centos7-node8 ~]# systemctl status nginx
[root@centos7-node8 ~]# systemctl restart nginx && systemctl enable nginx    #开机自启动
  • 测试

浏览器访问http://nginxIP 即可

制作nginxRPM安装包

  • 环境准备
[root@centos7-node8 ~]# yum -y install rpmbuild rpmdevtools     #工具安装
[root@centos7-node8 ~]# systemctl stop nginx && rm -fr /data/applications/nginx/     #关闭并删除之前的nginx
[root@centos7-node8 ~]# rpmdev-setuptree    #生成rpm制作环境目录
[root@centos7-node8 ~]# cd ~/rpmbuild/          #进入目录
[root@centos7-node8 rpmbuild]# tree ./
./
├── BUILD
├── RPMS
├── SOURCES
├── SPECS
└── SRPMS
  • 开始制作RPM
[root@centos7-node8 ~]# cd ~/rpmbuild/SOURCES/ &&  wget http://nginx.org/download/nginx-1.18.0.tar.gz
[root@centos7-node8 SOURCES]# cd ~/rpmbuild/SPECS/
[root@centos7-node8 SPECS]# vim nginx.spec
Name:           nginx
Version:        1.18.0
Release:        el7
Summary:        nginx
Group:          DevlopMent/Tools
License:        GPL
URL:            http://127.0.0.1
Source0:        %{name}-%{version}.tar.gz
BuildRequires:  gcc make
Requires:       pcre pcre-devel openssl openssl-devel zlib zlib-devel
%description
%prep
%setup -q
%build
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module --with-stream
make 
%install
make DESTDIR=%{buildroot} install
%files
/usr/local/nginx/*
%doc
%changelog
[root@centos7-node8 SPECS]# rpmbuild -bb nginx.spec     #生成rpm包
[root@centos7-node8 SPECS]# ls ~/rpmbuild/RPMS/x86_64/      #生成到的位置
[root@centos7-node8 SPECS]# cd ~/rpmbuild/RPMS/x86_64/
[root@centos7-node8 x86_64]# yum -y localinstall nginx-1.18.0-el7.x86_64.rpm     #本地安装

nginx配置文件解析

user  nobody;
worker_processes  auto;
error_log  logs/error.log warn;
events {
    worker_connections  60000;   
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    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;
        }
    }
}
  • user: 指定work进程用户,不要使用root
  • worker_processes: work进程数,用于处理请求,auto会根据服务器核心数创建work进程
  • error_log: 错误日志定义,级别设置成warn
  • worker_connections: work进程链接数设置,根据服务器配置尽量大点
[root@centos7-node8 conf]# vim /etc/security/limits.conf
* soft noproc 65535
* hard noproc 65535
* soft nofile 65535
* hard nofile 65535
  • include mime.types; 指定网页解析类型,(mime.types会制定不同类型的文件供浏览器请求解析)
  • default_type application/octet-stream; 默认格式则不会被浏览器解析,直接解析,这个取决于mime.types 文件的定义
  • keepalive_timeout 65; : 请求完成65秒断开链接,也可以设置成0。保证更多的请求
[root@centos7-node8 x86_64]# tcpdump -i any -nn 'port 80 and host 192.168.56.1'     #请求抓包测试
  • server: 配置虚拟主机
  • location: 请求定位

nginx日志定义

Nginx日志变量

  1. $remote_addr表示客户端IP,$time_local表示请求时间
  2. $request包含请求方法、请求的url、请求的协议
  3. $status表示响应状态码,$body_bytes_sent表示 响应的body的大小
  4. $http_referer表示请求的referer, $http_user_agent表示请求的客户端类型
  5. $http_x_forwarded_for可记录代理IP

更多的日志变量

  1. http://nginx.org/en/docs/varindex.html
  2. $remote_port、$time_iso8601、$uri
  3. $request_time、$upstream_response_time

Nginx使用Json格式日志

  • 方便elk日志采集
log_format  main  '$remote_addr - $remote_user [$time_iso8601] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

log_format json   '{"@timestamp":"$time_iso8601",'
                      '"remote_ip":"$remote_addr",'
                      '"status":$status,'
                      '"bytes":$body_bytes_sent,'
                      '"referer":"$http_referer",'
                      '"agent":"$http_user_agent",'
                      '"request_time":$request_time,'
                      '"request":"$uri"}';

nginx 的location

  • 属于server容器

  • location 正则匹配规则

    • cropy开头: location ~ /^cropy {}
    • php结尾: location ~ \.php$ {}
    • png,jpg结尾: location ~ \.(png|jpg)$ {}
    • 忽略大小写: location ~* \.(png|jpg)$ {}
  • location 优先级

    • 通用匹配:第二种的优先级比较高
    1. location / {}
     2. location /abc {}    #高优先级
    
    • 通用匹配和正则匹配的优先级: 2的优先级比较高
    1. location /abc {}
     2. location ~ ^/abc {}    #高优先级
    
    • 通用匹配之间的优先级: 第一个优先级比较高
     1. location ~ /^abc {}    #高优先级
     2. location ~/^abc/def {}
    
    • 精准匹配和正则匹配的优先级: 精准匹配的优先级会高(但是必须要精准)
    1. location ~ /^abc {}
     2. location = /abc/def {}  #优先级
    
  • 总结

    • 精准匹配 > 正则匹配 > 通用匹配
    • 正则多次命中,选第一个命中的location, 后面不在匹配
    • 通用多个命中,选匹配度最高的

nginx的root和alias配置

两个配置的区别:

  • root配置: 客户端请求http://www.baidu.com/img/a.html, 对应服务器的html/img/a.html
  • alias配置: 客户端请求http://www.baidu.com/img/a.html,对应服务器的html/a.html
# root配置
location /img/ {
    root html/img/ ;
}
#alias配置
location /img/ {
     alias html/;
}

nginx虚拟主机配置

  • 功能:

    • 一台服务器可以配置多特域名
    • 每个域名的网站内容是独立的
  • nginx配置文件简化

 [root@centos7-node8 nginx]#  cat conf/nginx.conf 
user  nobody;
worker_processes  auto;
error_log  logs/error.log warn;
events {
    worker_connections  60000;   
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_iso8601] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    
    log_format json   '{"@timestamp":"$time_iso8601",'
                      '"remote_ip":"$remote_addr",' 
                      '"status":$status,' 
                      '"bytes":$body_bytes_sent,' 
                      '"referer":"$http_referer",'
                      '"agent":"$http_user_agent",' 
                      '"request_time":$request_time,' 
                      '"request":"$uri"}';
    access_log  logs/access.log  json;
    sendfile        on;
    keepalive_timeout  0;
    gzip  on;
    include vhosts/*.conf;     #多配置文件
}
  • 在nginx安装目录下创建vhosts目录,然后写入配置文件即可
[root@centos7-node8 nginx]# mkdir vhosts
[root@centos7-node8 nginx]# vim vhosts/localhost.conf
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;
        }
}