NGINX服务搭建详解

nginx安装配置

NGINX常用模块

nginx模块分为nginx官方模块以及nginx第三方模块

Nginx编译选项模块作用
ngx_http_core_module包含一些核心的http参数配置,对应Nginx的配置区块部分
ngx_http_access_module访问控制模块,用来控制网站用户对Nginx的访问
ngx_http_gzip_module压缩模块,对Nginx返回的数据压缩,属于性能优化模块
ngx_http_fastcgi_modulefastcgi模块,和动态应用相关的模块,例如PHP
ngx_http_proxy_moduleproxy代理模块
ngx_http_upstream_module负载均衡模块,可以实现网站的负载均衡功能及节点的健康检查。
ngx_http_rewrite_moduleURL地址重写模块
ngx_http_limit_conn_module限制用户并发连接数及请求数模块
ngx_http_limit_req_module限制Nginx request processing rate根据定义的key
ngx_http_log_module访问日志模块,以指定的格式记录Nginx客户访问日志等信息
ngx_http_auth_basic_moduleWeb认证模块,设置Web用户通过账号密码访问Nginx
nginx_http_ssl_modulessI模块,用于加密的http连接,如https
环境准备
1.安装nginx方式
rpm包安装
yum安装
源代码安装

2.GCC编译环境安装:
yum install -y gcc gcc-c++ autoconf automake make

3.安装nginx一些所需的第三方系统库,比如nginx的静态资源压缩功能所需的gzip,lib库,nginx需要支持url重写所需的pcre库,perl开发的依赖库;以及nginx搭建加密站点https,所需的openssl依赖库等
yum install -y zlib zlib-devel openssl openssl-devel pcre pcre-devel wget httpd-tools vim 

4.配置系统基本环境(关闭防火墙,selinux)
systemctl stop firewalld && systemctl disable firewalld
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
编译安装nginx
1.下载程序源代码,可以从官网获取
wget http://nginx.org/download/nginx-1.20.0.tar.gz
也可以下载淘宝的nginx:tengine
wget http://tengine.taobao.org/download/tengine-2.3.0.tar.gz

2.解压缩nginx
[root@localhost opt]# tar -xzf nginx-1.20.0.tar.gz 
[root@localhost opt]# ls
nginx-1.20.0  nginx-1.20.0.tar.gz

3.进入源代码目录,查看有哪些内容
[root@localhost opt]# ll nginx-1.20.0
total 788
drwxr-xr-x. 6 1001 1001   4096 May  8 08:15 auto   检测系统模块依赖信息
-rw-r--r--. 1 1001 1001 311102 Apr 20 09:35 CHANGES  存放nginx的变化记录日志
-rw-r--r--. 1 1001 1001 474697 Apr 20 09:35 CHANGES.ru
drwxr-xr-x. 2 1001 1001   4096 May  8 08:15 conf  存放nginx的主配置文件目录
-rwxr-xr-x. 1 1001 1001   2590 Apr 20 09:35 configure  可执行脚本,用于释放文件的定制脚本
drwxr-xr-x. 4 1001 1001     68 May  8 08:15 contrib  提供vim插件,让配置文件颜色区分,更友好
drwxr-xr-x. 2 1001 1001     38 May  8 08:15 html  存放了标准的html页面文件
-rw-r--r--. 1 1001 1001   1397 Apr 20 09:35 LICENSE
drwxr-xr-x. 2 1001 1001     20 May  8 08:15 man
-rw-r--r--. 1 1001 1001     49 Apr 20 09:35 README 
drwxr-xr-x. 9 1001 1001     84 May  8 08:15 src  存放了nginx源代码的目录

4.开始准备编译三部曲
第一曲:进入软件源代码目录,执行编译脚本文件,制定安装路径,以及开启额外功能等
查看编译帮助信息
[root@localhost nginx-1.20.0]# ./configure --help
执行编译脚本文件,释放makefile等信息
[root@localhost nginx-1.20.0]# ./configure --prefix=/opt/nginx --with-http_gzip_static_module --with-http_ssl_module --with-http_flv_module --with-http_stub_status_module --with-threads --with-file-aio

第二曲:(如Windows的点击下一步安装) make
第三曲:(如Windows的开始安装) make install

5.查看nginx内的目录
[root@localhost nginx1-20]# ls
conf  html  logs  sbin
配置文件 静态文件 日志文件 二进制日志文件

6.如果想要在shell命令行直接使用nginx命令,而不用使用nginx绝对路径启动服务了,应配置nginx的环境变量
[root@localhost opt]# cat /etc/profile.d/nginx.sh 
export PATH=$PATH:/opt/nginx/sbin/
[root@localhost opt]# source /etc/profile

7.启动nginx 
[root@localhost ~]# nginx 
[root@localhost ~]# ps -aux | grep nginx
root       1276  0.0  0.0  46016  1136 ?        Ss   13:56   0:00 nginx: master process nginx
nobody     1277  0.0  0.0  46480  1908 ?        S    13:56   0:00 nginx: worker process
root       1279  0.0  0.0 112816   956 pts/0    R+   13:56   0:00 grep --color=auto nginx
重写加载配置文件:[root@localhost ~]# nginx -s reload

8.拷贝nginx语法高亮,发给vim的插件目录
[root@localhost ~]# mkdir .vim
[root@localhost ~]# cp -r /opt/nginx-1.20.0/contrib/vim/* .vim
nginx命令行
查看nginx帮助信息
[root@localhost ~]# nginx -h
nginx version: nginx/1.20.0
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help  输出nginx帮助信息
  -v            : show version and exit  列出nginx版本号
  列出nginx版本号和编译信息
  -V            : show version and configure options then exit
  检查nginx配置文件语法是否正确
  -t            : test configuration and exit
  检查配置,然后输出配置信息
  -T            : test configuration, dump it and exit
  在检查配置文件期间屏蔽非错误信息
  -q            : suppress non-error messages during configuration testing
  发送一个信号给nginx
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  设置nginx目录前缀
  -p prefix     : set prefix path (default: /opt/nginx/)
  -e filename   : set error log file (default: logs/error.log)
  指定配置文件
  -c filename   : set configuration file (default: conf/nginx.conf)
  覆盖设置一些默认参数
  -g directives : set global directives out of configuration file
  • 配置文件重读
1.检查当前的nginx进程
ps -ef | grep nginx
2.修改nginx.conf配置文件
3.重写加载nginx配置
nginx -s reload

nginx虚拟主机

虚拟主机指的就是一个独立的站点配置,是nginx默认支持的一个功能,它能够有自己独立的域名、独立的IP、独立的端口配置,能够配置完整的www服务;例如网站搭建,ftp服务搭建,邮件服务器代理等等。

并且nginx支持多虚拟主机,可以在一台机器上,同时运行多个网站

nginx的多虚拟主机,可以基于:

  • 多域名的形式
  • 多IP的形式
  • 多端口的形式

利用虚拟主机的功能,就不用为了运行一个网站,而单独的配置一个nginx服务器,或者单独的再运行一组nginx进程

利用nginx的多虚拟主机配置,我们就可以基于一台服务器,一个nginx进程,实现多个站点的配置

nginx单虚拟主机
  • nginx静态网站的搭建
    在这里插入图片描述
nginx静态资源压缩

nginx支持gzip压缩功能,经过gzip压缩之后的页面,图片,动态图这类的静态文件,能够压缩为原本的30%甚至更小,用户访问网站的体验会好很多

在主配置文件的http{}模块,添加:
	gzip  on;
    gzip_http_version 1.1;
    gzip_comp_level 4;
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/png image/gif;

nginx基于IP的多虚拟主机

环境准备

准备好Linux环境以及配置好3个IP地址
[root@localhost ~]# ip address add 192.168.100.91 dev eno16777736
[root@localhost ~]# ip address add 192.168.100.92 dev eno16777736

准备好的IP信息如下
[root@localhost ~]# ip a | grep 'inet 192'
    inet 192.168.100.90/24 brd 192.168.100.255 scope global eno16777736
    inet 192.168.100.91/32 scope global eno16777736
    inet 192.168.100.92/32 scope global eno16777736

添加nginx的配置,添加多个server{}

1.给nginx添加include包含语法,让其他目录下的配置文件参数,导入到nginx.conf中;这样的写法,能够让nginx每个配置文件看起来更简洁、清晰
mkdir /opt/nginx/conf/extra
在nginx.conf配置文件中的http{}标签中添加
include       extra/*.conf

2.创建3个站点目录
[root@localhost ~]# mkdir -p /www/{90,91,92}
[root@localhost ~]# echo "I'm 90 ,hello" >> /www/90/index.html
[root@localhost ~]# echo "I'm 91 ,hello" >> /www/91/index.html
[root@localhost ~]# echo "I'm 92 ,hello" >> /www/92/index.html

3.创建3个虚拟主机(以下只列举一个,其他2个虚拟主机只需修改IP和站点目录)
[root@localhost ~]# cat /opt/nginx/conf/extra/91.conf 
server{
	listen 192.168.100.91:80;  #基于IP主要点
	server_name _;
	charset utf-8;
	location / {
		root /www/91;
		index index.html index.htm;
	}
}

4.重新加载nginx配置文件;如果在修改了较多配置,在允许重启nginx的情况下,就重启;防止出现nginx有缓存的情况,出现页面无变化
nginx -s stop
nginx

5.测试
[root@localhost ~]# curl 192.168.100.92
I'm 92 ,hello
[root@localhost ~]# curl 192.168.100.90
I'm 90 ,hello
[root@localhost ~]# curl 192.168.100.91
I'm 91 ,hello
nginx基于域名多虚拟主机

基于多IP的虚拟主机,用的还是不多的,因为可能造成IP不足等情况;在没有特殊的需求下,用的更多的是基于多域名的虚拟主机

使用本地的hosts文件,进行访问测试

1.环境准备,修改本地hosts信息
[root@localhost ~]# tail -1 /etc/hosts
192.168.100.90 www.aa.com www.bb.com www.cc.com

2.创建3个站点目录
[root@localhost ~]# rm -rf /www/*
[root@localhost ~]# mkdir -p /www/{aa,bb,cc}
[root@localhost ~]# echo "welcome www.aa.com test" >> /www/aa/index.html
[root@localhost ~]# echo "welcome www.bb.com test" >> /www/bb/index.html
[root@localhost ~]# echo "welcome www.cc.com test" >> /www/cc/index.html

3.创建虚拟主机(以下只列举一个,其他2个虚拟主机只需修改域名和站点目录)
[root@localhost ~]# cat /opt/nginx/conf/extra/bb.conf
server{
	listen 80;
	server_name www.bb.com;  #基于域名主要点
	location / {
		root /www/bb;
		index index.html;
	}
}

4.重新启动nginx服务
nginx -s stop
nginx

5.测试
[root@localhost ~]# curl www.aa.com
welcome www.aa.com test
[root@localhost ~]# curl www.bb.com
welcome www.bb.com test
[root@localhost ~]# curl www.cc.com
welcome www.cc.com test
nginx基于端口的虚拟主机
1.准备站点目录
[root@localhost ~]# echo "port 80 test" > /www/aa/index.html 
[root@localhost ~]# echo "port 85 test" > /www/bb/index.html 
[root@localhost ~]# echo "port 8080 test" > /www/cc/index.html 

2.查看想使用的端口是否被占用
netstat -tunlp | grep 端口号

3.准备虚拟主机
[root@localhost ~]# cat /opt/nginx/conf/extra/bb.conf
server{
	listen 85;   #基于端口主要点
 	server_name _;
	location / {
		root /www/bb;
		index index.html;
	}
}

4.重新启动nginx服务
nginx -s stop
nginx

5.测试
[root@localhost ~]# curl 192.168.100.90:80
port 80 test
[root@localhost ~]# curl 192.168.100.90:85
port 85 test
[root@localhost ~]# curl 192.168.100.90:8080
port 8080 test

nginx访客日志

日志对于程序员是最重要的,可以用于问题排错,记录程序运行时的状态,一个好的日志配置,能够给运维人员,开发人员精准的问题定位功能。

nginx开启日志功能只需要在nginx.conf里面找到 log_format参数,定义日志的格式;以及定义日志存储的位置,日志的格式、路径、大小等等

定义在全局配置中(所有站点都往这个日志写)

nginx.conf配置日志功能代码如下
http {
    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"';
	
	#定义日志存储的位置
    #access_log  logs/access.log  main;
    #access_log  "pipe:rollback logs/access_log interval=1d baknum=7 maxsize=2G"  main;
    .......
    }

nginx的访客内容如下(对应上面的日志格式)

192.168.10.1 - - [11/May/2021:13:40:34 -0400] "GET / HTTP/1.1" 200 555 "-" "curl/7.55.1"

$remote_addr   记录访客的客户端IP地址
$remote_user   记录远程客户端的访客用户名
[$time_local]  记录访问的时间和地区信息
"$request"     记录用户的http请求的首行信息
$status         记录用户的http请求状态,也就是请求发出之后,响应的状态
$body_bytes_sent   记录服务器发给客户端的响应体数据字节大小
"$http_referer"   记录本次请求是从哪个链接过来的,可以根据refer信息来进行防盗链设置
"$http_user_agent"  记录客户端的访问信息,如浏览器信息,手机浏览器信息
"$http_x_forwarded_for"  可以捉到藏在代理服务器后面的真实客户端ip信息

由于写在http{}模块下属于全局配置,所以的站点访客日志都会写在一起,这样不方便管理和排查

所以我们可以给每个站点单独配置一个日志文件

1.修改配置文件如下
第一个站点
 server {
        listen       80;
        server_name  www.aa.com;

        charset utf-8;

        access_log  logs/aa_access.log  main;
        #access_log  "pipe:rollback logs/host.access_log interval=1d baknum=7 maxsize=2G"  main;

        location / {
            root   /www/aa;
            index  index.html index.htm;
        }
}
第二个站点
[root@localhost conf]# cat extra/bb.conf 
server{
	listen 80;
	server_name www.bb.com;
	access_log logs/bb_access.log;
	location / {
		root /www/bb;
		index index.html index.htm;
	}
}

2.重新加载配置文件
nginx -t
nginx -s reload

3.查看logs目录下是否新生成两个日志文件
[root@localhost nginx]# ls logs/
aa_access.log  access.log  bb_access.log  error.log  nginx.pid

4.测试
[root@localhost nginx]# curl www.aa.com
[root@localhost nginx]# cat logs/aa_access.log 
192.168.10.80 - - [11/May/2021:14:09:15 -0400] "GET / HTTP/1.1" 403 567 "-" "curl/7.29.0" "-"
[root@localhost nginx]# cat logs/bb_access.log 
[root@localhost nginx]# 

nginx目录浏览功能

能够将你的机器上的目录资料,提供一个展示,无论是谁都可以快速访问

修改nginx.conf配置,这个功能是在虚拟主机里定义的
[root@localhost nginx]# cat conf/extra/index.conf
server{
	listen 8080;
	server_name _;
	#让虚拟主机支持中文解析
	charset utf-8;

	#域名匹配,所有的请求都会进入如下的目录解析
	location / {
		root /www/index;
		#关闭虚拟主机的默认首页功能
		#index index.html;
		autoindex on;   #主要点
	}
}
[root@localhost nginx]# 

nginx状态页

nginx提供了status模块,用于检测nginx的请求连接信息,这个功能需要在编译安装的时候,添加–with-http_stub_status_module,才能使用

nginx -V 检查当前nginx是否支持status功能

当你支持status功能,我们可以添加一个conf配置文件,用于检测状态页的功能

在extra目录下,创建一个status.conf文件并写入一下内容
[root@localhost nginx]# cat conf/extra/status.conf 
server{
	listen 9000;
	server_name _;
	
	location / {
		stub_status on;  # 主要点
		access_log off;
	}
}

重新加载nginx配置
nginx -t
nginx -s reload

访问nginx状态页

192.168.10.80:9000
查看内容如下
Active connections: 1   显示正在处理的活动的连接数
server accepts handled requests request_time
 12 12 47 0
Reading: 0 Writing: 1 Waiting: 0 

server  nginx启动后一共处理的请求数
accepts handled  nginx启动后创建的握手数
requests    nginx一共处理了多少次请求
request_time  nginx处理的时间

Reading   nginx读取到客户端的headers数量
Writing	  nginx响应给客户端的headers数量
Waiting   nginx处理完毕请求之后,等待下一次的请求驻留的连接数

nginx错误日志

nginx能够把自身运行时故障的信息,也写到相对应的日志文件中,称之为error_log

对于错误信息的调试,也是运维人员维护nginx的一个重要手段

nginx想要使用error_log就得在nginx.conf配置文件中打开,可以写在全局配置中(把nginx所有配置的错误写入日志中),http{}模块(把全部虚拟主机的错误记录到日志中)或server{}虚拟主机中(只记录单个虚拟主机的错误)

错误日志的语法
error_log  file  level;

错误日志级别
debug
info
notice
warn
error
crit
alert
emerg
这个级别是越来越严重,级别写的越低,记录的日志越详细,没有必要...
级别越高,日志记录的内容就越少,生存环境下常用的是warn,error,crit模式
日志的级别,可能会给服务器增加额外的大量IO消耗;因此,根据你实际的工作需求定制

针对虚拟主机添加错误日志

server{
        listen 85;
        server_name www.bb.com;
        access_log logs/bb_access.log;
        error_log  logs/bb_error.log;

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

重新加载配置文件
nginx -t
nginx -s reload

查看是否生成日志文件
[root@www ~]# ls /opt/nginx/logs/
aa_access.log  access.log  bb_access.log  bb_error.log  error.log  nginx.pid

测试

nginx location匹配

nginx的location作用,是根据用户访问的url,进行不同的处理方式

针对用户请求的网站的url进行匹配处理,然后进行对应的处理

location相关语法

location [ = | ~ | ~* | ^~] url {
	#做出的相应的处理动作
}

#nginx有关location的匹配 符号如下
匹配符   匹配规则                      优先级
=       精确匹配                       1
^~      以某个字符开头,不做正则处理      2
~*      支持正则的匹配模式               3
/blog/   当你访问192.168.10.90/blog/xxx   4
/        通用匹配,不符合其他的location的匹配规则,就走到这里   5

案例演示

新创建一个配置文件
[root@www ~]# cat /opt/nginx/conf/extra/test_location.conf
server{
	listen 92;
	server_name _;

	#最低级匹配,不符合其他location就来这
	location / {
		return 401;
	}
	
	#优先级最高,精确匹配
	location = / {
		return 402
	}
	
	#以/blog/开头的url,来这里;如符合其他location,则以优先级判断
	location /blog/ {
		return 403;
	}

	#匹配任何以/img/开头的请求,不匹配正则
	location ^~ /img/ {
		return 404;
	}

	#匹配任何以.gif结尾的请求,支持正则
	location ~* \.(gif|jpg|jpeg)$ {
		return 500;
	}
}

重新加载配置文件
nginx -t
nginx -s reload

浏览器测试,注意优先级(如下只展示一部分)

在这里插入图片描述

nginx的url地址重写功能

nginx的url地址重写功能,主要是使用nginx提供的rewrite功能,且支持正则表达式

rewrite能够实现url的跳转,实现url规范化,根据请求的变量实现url跳转等等,基于url重写功能常见效果如下:

  • 对于爬虫程序的封禁,让其跳转到一个错误的页面
  • 动态的url,伪装成静态的html页面,便于搜索引擎的抓取
  • 新旧域名的更新,替换;www.aa.com >>> www.aa.com.cn

rewrite语法

rewrite  ^/(.*) www.baidu.com/$1   permanent
#解释
rewrite 是nginx地址重写的关键词指令,开启跳转功能
正则^/(.*) 表示匹配所有的请求,匹配成功后,跳转到后面指定的url地址
$1  是取出前面正则表达式分组的括号里的内容
permanent 表示301重定向的标记

rewrite结尾的参数标记如下

  • Last 规则匹配完成后,继续向下匹配新的location
  • break 本条规则匹配完成后,立即停止匹配动作
  • Redirct 返回302临时重定向状态码,浏览器地址栏显示跳转后的url,爬虫不会更新
  • Permanent 返回301永久重定向,浏览器地址显示跳转后的url,爬虫更新该网站url

last和break用于实现url重写,浏览器的地址栏不会发生变化

redirct和permanent也是用于url跳转,浏览器url地址栏发生变化,跳转到新的url地址栏

实现一个301 URL跳转
[root@www ~]# cat /opt/nginx/conf/extra/test_rewrite.conf
server{
	listen 98;
	server_name _;

	location / {
		rewrite ^/(.*) http://www.baidu.com/$1 permanent;
	}
}

重新加载配置文件
nginx -t
nginx -s reload

测试
浏览器输入192.168.10.80:98 是否会跳转到百度的页面

nginx访问认证

nginx提供了认证模块,语法是

location / {
	auth_basic 'string';  #开启认证功能并起名
	auth_basic_user_file  conf/htpasswd  #存放账号密码的文件
}
linux提供了密码生成命令
htpasswd是apache提供的密码生成工具,nginx也支持auth_basic模块,因此我们可以利用htpasswd命令生成账号密码文件,提供给nginx使用
yum install -y httpd-tools

#语法
htpasswd -bc .access username password
-b 在命令行中输入 账号密码
-c 创建密码文件
默认.access文件采用MD5加密方式来验证

实际操作案例

准备一个配置文件
[root@www ~]# cat /opt/nginx/conf/extra/bb.conf 
server{
	listen 85;
	server_name www.bb.com;
	access_log logs/bb_access.log;
	error_log  logs/bb_error.log;

	location / {
		root /www/bb;
		index index.html index.htm;
		auth_basic 'welcome to bb.com';
		auth_basic_user_file /opt/nginx/conf/extra/htpasswd;
	}
}

生成一个htpasswd密码文件
[root@www ~]# htpasswd -bc /opt/nginx/conf/extra/htpasswd qhj 123
Adding password for user qhj

重新加载配置文件
nginx -t
nginx -s reload

测试访问

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值