文章目录
1.nginx简介
nginx(发音同engine x)是一款高性能、轻量级、高并发的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。
nginx由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。
第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。
nginx下载地址
2.nginx的特性与优点
2.1nginx的特性
nginx是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:
- 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
使用epoll and kqueue作为开发模型 - nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
- nginx采用C进行编写不论系统资源开销还是CPU使用效率都比Perlbal要好很多
2.2 nginx的优点
- 高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数
- 内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)-
- 配置文件非常简单:风格跟程序一样通俗易懂
- 成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币
- 支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
- 内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问
- 节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头
- 稳定性高:用于反向代理,宕机的概率微乎其微
- 模块化设计:模块可以动态编译
- 外围支持好:文档全,二次开发和模块较多
- 支持热部署:可以不停机重载配置文件
- 支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化
3.nginx的功能及应用类别
3.1 nginx的基本功能
- 静态资源的web服务器,能缓存打开的文件描述符
- http、smtp、pop3协议的反向代理服务器
缓存加速、负载均衡 - 支持FastCGI(fpm,LNMP),uWSGI(Python)等
- 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
支持SSL
3.2 nginx的扩展功能
- 基于名称和IP的虚拟主机
- 支持keepalive
- 支持平滑升级
- 定制访问日志、支持使用日志缓冲区提高日志存储性能
- 支持URL重写
- 支持路径别名
- 支持基于IP及用户的访问控制
- 支持速率限制,支持并发数限制
3.3 nginx的应用类别
- 使用nginx结合FastCGI运行PHP、JSP、Perl等程序
- 使用nginx作反向代理、负载均衡、规则过滤
- 使用nginx运行静态HTML网页、图片
- nginx与其他新技术的结合应用
4. nginx的模块与工作原理
nginx由内核和模块组成。其中,内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location block(location是nginx配置中的一个指令,用于URL匹配),而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。
4.1 nginx的模块分类
nginx的模块从结构上分为核心模块、基础模块和第三方模块
- HTTP模块、EVENT模块和MAIL模块等属于核心模块
- HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块属于基本模块
- HTTP Upstream模块、Request Hash模块、Notice模块和HTTP Access Key模块属于第三方模块
用户根据自己的需要开发的模块都属于第三方模块。正是有了如此多模块的支撑,nginx的功能才会如此强大
nginx模块从功能上分为三类,分别是:
- Handlers(处理器模块)。此类模块直接处理请求,并进行输出内容和修改headers信息等操作。handlers处理器模块一般只能有一个
- Filters(过滤器模块)。此类模块主要对其他处理器模块输出的内容进行修改操作,最后由nginx输出
- Proxies(代理器模块)。就是nginx的HTTP Upstream之类的模块,这些模块主要与后端一些服务比如fastcgi等操作交互,实现服务代理和负载均衡等功能
nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等 - nginx基本模块:所谓基本模块,指的是nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:
- 核心模块:基本功能和指令,如进程管理和安全。常见的核心模块指令,大部分是放置在配置文件的顶部
- 事件模块:在Nginx内配置网络使用的能力。常见的events(事件)模块指令,大部分是放置在配置文件的顶部
- 配置模块:提供包含机制
4.2 nginx的工作原理
nginx的模块直接被编译进nginx,因此属于静态编译方式。
启动nginx后,nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。
在解析配置文件时,nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。
5.LNMP部署(Linux+Nginx+MYSQL+PHP)
5.1安装nginx
#关闭防火墙和selinux
[root@localhost ~]# systemctl disable --now firewalld.service
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@localhost ~]# setenforce 0[root@localhost ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
#安装依赖环境
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make wget vim
[root@localhost ~]# yum -y groups mark install 'Development Tools'
#创建日志存放目录
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx
#下载nginx
[root@localhost ~]# cd /usr/src/
[root@localhost src]# wget https://nginx.org/download/nginx-1.20.2.tar.gz
#编译安装
[root@localhost src]# tar xf nginx-1.20.2.tar.gz
[root@localhost src]# cd nginx-1.20.2/
[root@localhost nginx-1.20.2]# ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log
[root@localhost src]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
[root@localhost ~]# cd /usr/local/
[root@localhost local]# ls //安装完成后安装目录下会有nginx目录
bin etc games include lib lib64 libexec nginx sbin share src
5.2配置nginx
#设置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost ~]# source /etc/profile.d/nginx.sh
[root@localhost ~]# which nginx
/usr/local/nginx/sbin/nginx
#nginx启动
[root@localhost ~]# nginx
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
#nginx关闭
[root@localhost ~]# nginx -s stop
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
#nginx重启
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
#配置service文件
[root@localhost ~]# cd /usr/lib/systemd/system/
[root@localhost system]# cp -r sshd.service nginx.service
[root@localhost system]# cat nginx.service
[Unit]
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecReload=/usr/local/nginx/sbin/nginx -s reload
KillMode=process
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target
[root@localhost system]# systemctl daemon-reload
[root@localhost ~]# systemctl enable --now nginx.service //设置开机自启
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@localhost ~]# systemctl status nginx.service
● nginx.service
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: >
Active: active (running) since Sat 2022-09-03 21:48:46 CST; 1min 11s ago
5.3安装mysql
#配置依赖环境
[root@localhost ~]# useradd -r -M -s /sbin/nologin mysql
[root@localhost ~]# yum install -y ncurses-compat-libs
#下载安装包(包比较大建议浏览器下载使用工具拖进去)
[root@localhost src]# ls
mysql-8.0.26-linux-glibc2.12-x86_64.tar.xz nginx-1.20.2 nginx-1.20.2.tar.gz
#解压软件包
[root@localhost src]# tar xf mysql-8.0.26-linux-glibc2.12-x86_64.tar.xz -C /usr/local/
[root@localhost ~]# cd /usr/local/
[root@localhost local]# mv mysql-8.0.26-linux-glibc2.12-x86_64/ mysql
[root@localhost local]# chown -R mysql.mysql mysql/
5.4配置mysql
#设置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
[root@localhost ~]# source /etc/profile.d/mysql.sh
[root@localhost ~]# which mysql
/usr/local/mysql/bin/mysql
#软连接 lib库 man文档
[root@localhost ~]# ln -s /usr/local/mysql/include/ /usr/include/mysql
[root@localhost ~]# cat /etc/ld.so.conf.d/mysql.conf
/usr/local/mysql/lib
[root@localhost ~]# vim /etc/man_db.conf
MANDATORY_MANPATH /usr/local/mysql/man
#建立数据存放目录
[root@localhost ~]# mkdir -p /opt/data
[root@localhost ~]# chown -R mysql.mysql /opt/data/
[root@localhost ~]# ll /opt/
总用量 0
drwxr-xr-x. 2 mysql mysql 6 9月 3 22:03 data
#格式化
[root@localhost ~]# mysqld --initialize --user=mysql --datadir=/opt/data/
2022-09-03T14:03:56.825183Z 0 [System] [MY-013169] [Server] /usr/local/mysql/bin/mysqld (mysqld 8.0.26) initializing of server in progress as process 260931
2022-09-03T14:03:56.833359Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2022-09-03T14:03:57.477079Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2022-09-03T14:03:58.287217Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
2022-09-03T14:03:58.287519Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
2022-09-03T14:03:58.431026Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: 2&a?oayBQSqt //临时密码
[root@localhost ~]# echo '2&a?oayBQSqt' > passwd
[root@localhost ~]# cat passwd
2&a?oayBQSqt
#生成配置文件
[root@localhost ~]# vim /etc/my.cnf
[root@localhost ~]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
#配置服务启动脚本
[root@localhost ~]# cd /usr/local/mysql/support-files/
[root@localhost support-files]# cp mysql.server mysqld
[root@localhost support-files]# vim mysqld //搜索basedir 并修改成下面这样
basedir=/usr/local/mysql
datadir=/usr/local/data
#启动mysql
[root@localhost ~]# /usr/local/mysql/support-files/mysqld start
Starting MySQL.Logging to '/opt/data/localhost.localdomain.err'.
SUCCESS!
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 70 *:33060 *:*
LISTEN 0 128 *:3306 *:*
#修改mysql的root用户密码
[root@localhost ~]# mysql -uroot -p'2&a?oayBQSqt'
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.26
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'kurumi123!';
Query OK, 0 rows affected (0.00 sec)
mysql> exit
Bye
#测试密码
[root@localhost ~]# mysql -uroot -pkurumi123!
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.26 MySQL Community Server - GPL
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
5.5配置mysql的service文件
[root@localhost ~]# /usr/local/mysql/support-files/mysqld stop //关闭
Shutting down MySQL. SUCCESS!
[root@localhost ~]# cd /usr/lib/systemd/system
[root@localhost system]# cp sshd.service mysqld.service
[root@localhost system]# vim mysqld.service
[root@localhost system]# cat mysqld.service
[Unit]
Description=mysql server daemon
After=network.target sshd-keygen.target
[Service]
Type=forking
ExecStart=/usr/local/mysql/support-files/mysqld start
ExecStop=/usr/local/mysql/support-files/mysqld stop
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target
[root@localhost system]# systemctl daemon-reload
[root@localhost ~]# systemctl enable --now mysqld.service //设置开机自启
Created symlink /etc/systemd/system/multi-user.target.wants/mysqld.service → /usr/lib/systemd/system/mysqld.service.
[root@localhost ~]# systemctl status mysqld.service
● mysqld.service - mysql server daemon
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset:>
Active: active (running) since Sat 2022-09-03 22:12:50 CST; 24s ago
5.6安装php
#下载php软件包
[root@localhost ~]# cd /usr/src/
[root@localhost src]# wget https://www.php.net/distributions/php-8.1.10.tar.gz
[root@localhost src]# ls
mysql-8.0.26-linux-glibc2.12-x86_64.tar.xz nginx-1.20.2.tar.gz
nginx-1.20.2 php-8.1.10.tar.gz
#安装依赖包
[root@localhost ~]# yum -y install autoconf freetype gd libpng libpng-devel libjpeg libxml2 libxml2-devel zlib curl curl-devel net-snmp-devel libjpeg-devel php-ldap openldap-devel openldap-clients freetype-devel gmp-devel libzip libzip-devel sqlite-devel
安装oniguruma 依赖包
[root@localhost ~]# yum install autoconf automake libtool -y
[root@localhost ~]# wget https://github.com/kkos/oniguruma/archive/v6.9.4.tar.gz -O oniguruma-6.9.4.tar.gz
[root@localhost ~]# tar xf oniguruma-6.9.4.tar.gz && cd oniguruma-6.9.4
[root@localhost oniguruma-6.9.4]# ./autogen.sh && ./configure --prefix=/usr
Generating autotools files.
[root@localhost oniguruma-6.9.4]# make && make install
#源码安装php
[root@localhost ~]# cd /usr/src/
[root@localhost src]# tar xf php-8.1.10.tar.gz
[root@localhost src]# cd php-8.1.10/
[root@localhost php-8.1.10]# ./configure --prefix=/usr/local/php8 --with-config-file-path=/usr/local/php8/etc --enable-fpm --with-fpm-user=nginx --with-fpm-group=nginx --enable-mysqlnd --with-mysqli --with-pdo-mysql --enable-opcache --with-pcre-jit --enable-gd --with-jpeg --with-freetype --with-gettext --with-curl --with-openssl --enable-sockets --enable-mbstring --enable-xml --with-zip --with-zlib --with-snmp --with-mhash --enable-ftp --enable-bcmath --enable-soap --enable-shmop --enable-sysvsem --enable-pcntl --with-gmp
#看到下面这个就是编译成功
+--------------------------------------------------------------------+
| License: |
| This software is subject to the PHP License, available in this |
| distribution in the file LICENSE. By continuing this installation |
| process, you are bound by the terms of this license agreement. |
| If you do not agree with the terms of this license, you must abort |
| the installation process at this point. |
+--------------------------------------------------------------------+
Thank you for using PHP.
#安装
[root@localhost php-8.1.10]# make && make install
5.7配置php
#配置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/php8/bin:$PATH' > /etc/profile.d/php8.sh
[root@localhost ~]# source /etc/profile.d/php8.sh
[root@localhost ~]# which php
/usr/local/php8/bin/php
#配置php-fpm
[root@localhost ~]# cd /usr/src/php-8.1.10/
[root@localhost php-8.1.10]# cp php.ini-production /etc/php.ini
cp:是否覆盖'/etc/php.ini'? y
[root@localhost php-8.1.10]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@localhost php-8.1.10]# chmod +x /etc/rc.d/init.d/php-fpm
[root@localhost php-8.1.10]# cp /usr/local/php8/etc/php-fpm.conf.default /usr/local/php8/etc/php-fpm.conf
[root@localhost php-8.1.10]# cp /usr/local/php8/etc/php-fpm.d/www.conf.default /usr/local/php8/etc/php-fpm.d/www.conf
#开启php
[root@localhost ~]# service php-fpm start
Starting php-fpm done
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 127.0.0.1:9000 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 70 *:33060 *:*
LISTEN 0 128 *:3306 *:*
5.8配置nginx.conf文件
#在43行到46行
location / {
root html;
index index.php index.html index.htm; //添加idnex.php
}
#在65行到71行
##取消注释
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 添加这一行(脚本文件请求的路径)
include fastcgi_params;
}
#编写php测试文件
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# vim index.php
[root@localhost html]# cat index.php
<?php
phpinfo();
?>
#重启服务
[root@localhost ~]# systemctl restart nginx.service
浏览器访问测试
6.平滑升级nginx
源码升级软件或添加功能模块的步骤:
1.准备升级包或功能包
2.获取升级前版本的编译参数
3.解压新版本,使用conf igure进行配置,配置时加上升级前版本的编译参数,然后添加新功能模块
4.编译(禁止执行make install安装)
5.将老程序停止并使用新程序和老配置文件启动新版本
6.如果第5步成功,并能够正常访问,则备份老版本的程序并同时复制新版本程序覆盖老版本并重启
7.验证
#准备升级包和功能包
[root@localhost ~]# yum -y install git
[root@localhost ~]# wget https://nginx.org/download/nginx-1.23.1.tar.gz
[root@localhost ~]# git clone https://github.com/openresty/echo-nginx-module.git
正克隆到 'echo-nginx-module'...
remote: Enumerating objects: 3047, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (20/20), done.
remote: Total 3047 (delta 11), reused 19 (delta 9), pack-reused 3018
接收对象中: 100% (3047/3047), 1.17 MiB | 68.00 KiB/s, 完成.
处理 delta 中: 100% (1635/1635), 完成.
[root@localhost ~]# tar xf nginx-1.23.1.tar.gz
[root@localhost ~]# ls
anaconda-ks.cfg echo-nginx-module nginx-1.23.1 nginx-1.23.1.tar.gz
#备份一份nginx启动文件
[root@localhost ~]# cd /usr/local/nginx/sbin/
[root@localhost sbin]# ls
nginx
[root@localhost sbin]# cp /usr/local/nginx/sbin/nginx{,.bak}
[root@localhost sbin]# ls
nginx nginx.bak
[root@localhost nginx-1.23.1]# pwd
/root/nginx-1.23.1
[root@localhost nginx-1.23.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module
[root@localhost nginx-1.23.1]# make
[root@localhost nginx-1.23.1]# cd objs/ //编译完成后objs有nginx主程序
[root@localhost objs]# ls
addon Makefile nginx.8 ngx_auto_headers.h ngx_modules.o
autoconf.err nginx ngx_auto_config.h ngx_modules.c src
#新版本-V查看
[root@localhost ~]# ./nginx-1.23.1/objs/nginx -V
nginx version: nginx/1.23.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)
built with OpenSSL 1.1.1k FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module //多了echo的模块
#老版本-V
[root@localhost ~]# nginx -V
nginx version: nginx/1.20.2
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)
built with OpenSSL 1.1.1k FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
[root@localhost ~]# nginx -s stop //停掉老版本的nginx
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
#测试启动新版本的nginx
[root@localhost nginx-1.23.1]# ./objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx-1.23.1]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
#关闭
[root@localhost nginx-1.23.1]# ./objs/nginx -s stop -c /usr/local/nginx/conf/nginx.conf
[root@localhost sbin]# pkill nginx //停不掉用pkill
[root@localhost nginx-1.23.1]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
#复制主程序
[root@localhost nginx-1.23.1]# cp objs/nginx /usr/local/nginx/sbin/
cp:是否覆盖'/usr/local/nginx/sbin/nginx'? y
[root@localhost nginx-1.23.1]# cd /usr/local/nginx/sbin/
[root@localhost sbin]# ls
nginx nginx.bak //nginx为新版本 nginx.bak为老
测试
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
echo "test"; //添加echo
root html;
index index.html index.htm;
}
#查看新老语法
[root@localhost conf]# nginx.bak -t //老版本不支持echo报错了
nginx: [emerg] unknown directive "echo" in /usr/local/nginx/conf/nginx.conf:45
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
[root@localhost conf]# nginx -t //新版本正常
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost conf]# nginx -s reload //启动新版本的nginx
[root@localhost conf]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@localhost conf]# curl 192.168.220.10 //用命令行访问(使用浏览器访问不会有效果)
test
7.loaction使用
location区段,通过指定模式来与客户端请求的URI相匹配
//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能
//语法:location [ 修饰符 ] pattern {......}
常用修饰符说明:
查找顺序和优先级:由高到底依次为
- 带有=的精确匹配优先
- 正则表达式按照他们在配置文件中定义的顺序
- 带有^~修饰符的,开头匹配
- 带有或*修饰符的,如果正则表达式与URI匹配
- 没有修饰符的精确匹配
优先级次序如下:
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )
注:如果没有修饰符按先后顺序访问
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
#access_log logs/host.access.log main; //添加下面三行测试
location / {
echo 'test';
}
location /xixi {
echo 'xixi';
}
location /hehe {
echo 'hehe';
}
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# curl 192.168.220.10 //默认跟下为test
test
[root@localhost conf]# curl 192.168.220.10/xixi //访问指定的目录
xixi
[root@localhost conf]# curl 192.168.220.10/hehe
hehe
访问的名字不能一样否则会报错
location / {
echo 'test';
}
location /xixi { //当两个都是xixi时
echo 'xixi';
}
location /xixi { //也是xixi
echo 'hehe';
}
[root@localhost ~]# nginx -s reload //会发生报错因为有两个一样的
nginx: [emerg] duplicate location "/xixi" in /usr/local/nginx/conf/nginx.conf:55
=精确匹配
location / {
echo 'test';
}
location /xixi {
echo 'xixi';
}
location = /xixi { //名字一样但是=的优先级大
echo 'hehe';
}
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# curl 192.168.220.10/xixi //所以会访问到hehe
hehe
~区分大小写
location / {
echo 'test';
}
location /xixi {
echo 'xixi';
}
location ~ /xixi { //添加~
echo 'hehe';
}
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# curl 192.168.220.10/Xixi //因为区分大小写找不带Xixi所以访问到默认
test
[root@localhost conf]# curl 192.168.220.10/xixi //换成xixi后访问到了 没有报错因为~的优先级大
hehe
*~不区分大小写
location / {
echo 'test';
}
location /xixi {
echo 'xixi';
}
location ~* /xixi {
echo 'hehe';
}
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# curl 192.168.220.10/XIXI //~*不区分大小写
hehe
[root@localhost conf]# curl 192.168.220.10/xixi
hehe
~^前缀匹配
location / {
echo 'test';
}
location ^~/xixi { //优先级比~高
echo 'xixi';
}
location ~ /xixi {
echo 'hehe';
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# curl 192.168.220.10/xixi //访问
xixi
8.访问控制
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
配置测试文件
[root@localhost html]# pwd
/usr/local/nginx/html
[root@localhost html]# echo 'hello world' > index.html
[root@localhost html]# systemctl restart nginx.service
[root@localhost html]# curl 192.168.220.10
hello world
[root@localhost html]# curl 127.0.0.1 //本地访问
hello world
#cmd也可以访问
C:\Users\hp>curl 192.168.220.10
hello world
只允许192.168.220.1访问
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
location / {
allow 192.168.220.1; //允许真机访问
deny all; //拒绝所有
root html;
index index.html index.htm;
}
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# curl 192.168.220.10 //403被拒绝了
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>
C:\Users\hp>curl 192.168.220.10 //cmd可以正常访问
hello world
9.基于用户认证
[root@localhost conf]# yum install httpd-tools -y //安装httpd工具包 用于生成密码
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
location / {
root html;
index index.html index.htm; //用户可以访问到默认页面
}
location /xixi { //想要访问xixi页面时需要密码
auth_basic "欢迎信息"; //提示信息
auth_basic_user_file "/usr/local/nginx/conf/.pass"; //密码存放位置
root html;
index index.html;
}
#生成用户和密码
[root@localhost conf]# htpasswd -cm /usr/local/nginx/conf/.pass kurumi
New password:
Re-type new password:
Adding password for user kurumi
[root@localhost conf]# cat .pass
kurumi:$apr1$hFlRbU7N$JN6Nd6A3TUgjelRoyN7.M.
[root@localhost conf]# systemctl restart nginx.service //重启
访问默认页面
访问xixi
需要登陆并验证密码
10.https配置
生成证书
[root@localhost ~]# cd /etc/pki/
[root@localhost pki]# mkdir CA
[root@localhost pki]# cd CA/
[root@localhost CA]# mkdir private
[root@localhost CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.......+++++
......+++++
e is 65537 (0x010001)
[root@localhost CA]# ls private/
cakey.pem
** CA生成自签署证书**
[root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN //国家
State or Province Name (full name) []:HB //省
Locality Name (eg, city) [Default City]:WH //市
Organization Name (eg, company) [Default Company Ltd]:HHHH //公司
Organizational Unit Name (eg, section) []:www.example.com //域名
Common Name (eg, your name or your server's hostname) []:www.example.com
Email Address []:
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial
客户端(例如httpd服务器)生成密钥
[root@localhost ~]# cd /usr/local/nginx/conf/ && mkdir ssl && cd ssl
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.......................................................+++++
..............................................................+++++
e is 65537 (0x010001)
[root@localhost ssl]# ls
nginx.key
客户端生成证书签署请求
[root@localhost ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:HHHH
Organizational Unit Name (eg, section) []:www.example.com
Common Name (eg, your name or your server's hostname) []:www.example.com
Email Address []:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
CA签署客户端提交上来的证书
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
Serial Number: 1 (0x1)
Validity
Not Before: Sep 4 14:08:25 2022 GMT
Not After : Sep 4 14:08:25 2023 GMT
Subject:
countryName = CN
stateOrProvinceName = HB
organizationName = HHHH
organizationalUnitName = www.example.com
commonName = www.example.com
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
19:E8:F8:09:0D:1A:87:36:2E:FF:7B:6D:C6:DB:2B:FD:53:9E:CD:07
X509v3 Authority Key Identifier:
keyid:F0:D8:21:EB:0B:0B:7B:15:80:BF:A2:86:C1:00:CD:BF:0C:04:4B:72
Certificate is to be certified until Sep 4 14:08:25 2023 GMT (365 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@localhost ssl]# ls
nginx.crt nginx.csr nginx.key
生成私钥,生成证书签署请求并获得证书,然后在nginx.conf中配置如下内容:
#搜素HTTP 取消下面的注释 并修改两行
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate /usr/local/nginx/conf/ssl/nginx.crt; //这个
ssl_certificate_key /usr/local/nginx/conf/ssl/nginx.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@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 0.0.0.0:443 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
11.rewrite
语法:rewrite regex replacement flag;,如:
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
此处的$1用于引用(.*.jpg)匹配到的内容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;
如上例所示,replacement可以是某个路径,也可以是某个URL
常见的flag
rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)
nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:
#创建images目录 用于存放图片
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir images
[root@localhost html]# ls images/
1.jpg
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf //添加location
location /images {
root html;
}
[root@localhost conf]# systemctl restart nginx.service
浏览器访问
[root@localhost html]# pwd
/usr/local/nginx/html
[root@localhost html]# ls
50x.html images index.html
[root@localhost html]# mv images/ imgs //正常情况下当修改了目录名 就不能
[root@localhost conf]# vim nginx.conf
location /images {
rewrite ^/images/(.*)$ /imgs/$1 break; //所有以images开头访问的 用imgs响应
}
[root@localhost html]# nginx -s reload
浏览器访问images/1.jpg
使用imgs/1.jpg也可以访问
location /images {
rewrite ^/images/(.*\.jpg)$ https://t7.baidu.com/it/u=2511982910,2454873241&fm=193&f=GIF break; //将响应换为网页图片的地址
}
[root@localhost conf]# systemctl restart nginx.service
浏览器访问images/1.jpg 跳转到了网页图片
当前匹配结束 继续匹配下一个
location /images{
rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;
}
location /imgs {
rewrite ^/imgs/(.*\.jpg)$ http://www.baidu.com break;
}
[root@localhost conf]# systemctl restart nginx.service
访问images/1.jpg 进行下一个匹配 跳转到百度
redirect临时重定向
location /images{
rewrite ^/images/(.*\.jpg)$ /imgs/$1 redirect;
}
[root@localhost conf]# systemctl restart nginx.service
permanent永久重定向
location /images{
rewrite ^/images/(.*\.jpg)$ /imgs/$1 permanent;
}
[root@localhost conf]# nginx -s reload
if
语法:if (condition) {...}
应用场景:
server段
location段
常见的condition
变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
正则表达式的模式匹配操作
~:区分大小写的模式匹配检查
~*:不区分大小写的模式匹配检查
!~和!~*:对上面两种测试取反
测试指定路径为文件的可能性(-f,!-f)
测试指定路径为目录的可能性(-d,!-d)
测试文件的存在性(-e,!-e)
检查文件是否有执行权限(-x,!-x)
基于浏览器实现分离案例
if ($http_user_agent ~ Firefox) {
rewrite ^(.*)$ /firefox/$1 break;
}
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
if ($http_user_agent ~ Chrome) {
rewrite ^(.*)$ /chrome/$1 break;
}
防盗链案例
location ~* \.(jpg|gif|jpeg|png)$ {
valid_referers none blocked www.idfsoft.com;
if ($invalid_referer) {
rewrite ^/ http://www.idfsoft.com/403.html;
}
}