使用nginx搭建的各种服务

2023-10-27

一、nginx搭建文件服务器

1、安装nginx

#!/bin/bash
#安装nginx的脚本文件
#先按照nginx的依赖
yum -y install gcc openssl-devel pcre-devel &> /dev/null
echo "nginx依赖gcc,openssl-devel,pcre-devel安装完成"
#安装nginx
cd /root
tar -xf nginx-1.23.3.tar.gz
cd nginx-1.23.3
./configure \
--with-http_ssl_module \
--with-stream \
--with-http_stub_status_module
sleep 1
echo "nginx编译完成"
make && make install
sleep 1
echo "nginx安装完成"
cp /usr/local/nginx/sbin/nginx /usr/local/sbin/
nginx -V
nginx
echo "nginx已开启,可以在浏览器端输入本机IP地址验证。" 

注意:在安装nginx的过程中,若是没有指定用户,nginx会以nobody这个用户来处理各种请求。nginx启动是以root用户启动的。

root       1426  0.0  0.2  46116  1184 ?        Ss   08:28   0:00 nginx: master process nginx
nobody     1427  0.1  0.5  46584  2556 ?        S    08:28   0:01 nginx: worker process

注意:实际上干活的是work process进程,master process不干活。nginx是一个多进程的程序。
注意:nginx是按照在名为proxy的主机上的,该主机有两个IP地址。分别是192.168.4.5、192.168.2.5。

2、修改nginx配置文件

  1. 修改配置文件的时候,先将配置文件做一个备份。
cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak
  1. 修改配置文件
17 http {
 18     include       mime.types;
 19     default_type  application/octet-stream;
 27     sendfile        on;
 31     keepalive_timeout  65;
 35     autoindex on;	//要搭建文件系统,这个功能必须要开启
 36     autoindex_exact_size on;  //同样要搭建文件系统,这个要开启。
 37     autoindex_localtime on;   //要开启,搭建文件系统。
 38     charset utf-8;    //为了防止中文乱码,这个要开启。
 39     server {
 40         listen       80;
 41         server_name  localhost;
 47         location / {
 48             root   html;    //可以将要分享的文件目录,放在html这个目录下。
 49             index  index.html index.htm;
 50         }
 56         error_page   500 502 503 504  /50x.html;
					  location = /50x.html {
 58             root   html;
 59         }
 83     }
 88     server {
 89         listen       8080;
 90         server_name  localhost;
 91 
 92         location / {
 93             if ($request_filename ~* ^.*?\.(txt|pdf|doc|xls|png|jpg|jpeg)$){
 94                 add_header Content-Disposition "attachment;";
 95             }    //这是一个逻辑判断,要是以.txt|.pdf|.doc|.xls|.png|.jpg|.jpeg结尾的文件
                  	直接下载,不使用浏览器解析。
 96             root   /home/static;    //要分享的文件目录的根目录,也就是说/home/static这个
                    	目录要共享到文件服务器。
 97             index  index.html index.htm;
 98         }
 99     }
100 }

注:本次搭建了两个文件系统,一个在80端口监听,一个在8080端口监听。两个要共享的目录一个在/usr/local/nginx/html下,一个在/home/static下。

 35     autoindex on;	//要搭建文件系统,这个功能必须要开启
 36     autoindex_exact_size on;  //同样要搭建文件系统,这个要开启。
 37     autoindex_localtime on;   //要开启,搭建文件系统。
 38     charset utf-8;    //为了防止中文乱码,这个要开启。

注:这是http全局配置,该配置写在了http里面,serve外面。所以,对于http服务来说,是全局配置。要想只让这一个web服务是文件服务器服务,可以将该配置写在server里面。

3、客户端验证

![image.png](https://img-blog.csdnimg.cn/img_convert/8d8ccb13164dd9efbe10ae71216b5831.png#averageHue=#fdfbfb&clientId=u64da39d2-d75b-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u9c33b3df&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=78986&status=done&style=none&taskId=u60be1edc-2ac5-4b62-b815-f078fb6eb0c&title=&width=1536.8)
![image.png](https://img-blog.csdnimg.cn/img_convert/2a3f4ac45a41f8de207905421ebb3915.png#averageHue=#fdfbfb&clientId=u64da39d2-d75b-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u17d8f256&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=70121&status=done&style=none&taskId=udddc417a-610d-439d-80a5-35f8d717198&title=&width=1536.8)
注意:防火墙和SELinux要关闭。

二、使用nginx实现web服务用户认证

1、修改nginx配置文件

 88     server {
 89         listen       8080;
 90         server_name  localhost;
 91         auth_basic "input userAndpassword:";  //认证提示符信息
 92         auth_basic_user_file "/usr/local/nginx/pass";  //认证的密码文件
 93         location / {
 94             if ($request_filename ~* ^.*?\.(txt|pdf|doc|xls|png|jpg|jpeg)$){
 95                 add_header Content-Disposition "attachment;";
 96             }
 97             root   /home/static;
 98             index  index.html index.htm;
 99         }
100     }

2、生成密码文件

  • 首先查看httpd-tools是否安装,一般安装nginx默认会安装。
yum -y install httpd-tools
  • 生成密码文件:
[root@proxy ~]# htpasswd -c /usr/local/nginx/pass tom  //生成密码文件并创建一个Tom用户
New password:     				//输入要创建的密码
Re-type new password:     //确认密码
Adding password for user tom
[root@proxy ~]# 
 

注意:因为在nginx.conf配置文件中,密码文件的存放位置在/usr/local/nginx/目录下,所以生成的密码文件要存放在该位置。这点和htppasswd -c /usr/local/nginx/pass对应上了。

3、重载nginx并在客户端验证

  • 重载nginx:
nginx  -t    //查看nginx配置文件是否错误

[root@proxy ~]# 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
//这种情况说明nginx配置文件正确

nginx  -s  reload   //nginx重载
  • 客户端验证:

![image.png](https://img-blog.csdnimg.cn/img_convert/b101aa89d888415c4f448b0f32eecc19.png#averageHue=#fefcfc&clientId=u4758c9b3-3367-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=ua0703553&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=65502&status=done&style=none&taskId=u9ecd2586-624d-4aae-96c5-94ab7765f65&title=&width=1536.8)
![image.png](https://img-blog.csdnimg.cn/img_convert/84b86d074d7221d6146f2d15c22740dc.png#averageHue=#fdfafa&clientId=u4758c9b3-3367-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u2c16c4ac&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=99203&status=done&style=none&taskId=u11f51604-65ec-4a46-b2c6-ccbfdc0dbbd&title=&width=1536.8)

三、基于域名的虚拟主机

  1. 实现两个基于域名的虚拟主机,域名分别为www.a.com、www.b.com
  2. www.a.com所提供的服务,需要进行用户认证,用户名tom,密码tom。

1、修改nginx配置

 39     server {
 40         listen       80;
 41         server_name  www.b.com;
 42 
 43         #charset koi8-r;
 44 
 45         #access_log  logs/host.access.log  main;
 46 
 47         location / {
 48             root   html;
 49             index  index.html index.htm;
 50         }
 51 
 52         error_page  404              /404.html;
 53 
 54         # redirect server error pages to the static page     /50x.html
 55         #
 56         error_page   500 502 503 504  /50x.html;
 57         location = /50x.html {
 58             root   html;
 59         }

 88     server {
 89         listen       80;
 90         server_name  www.a.com;
 91         auth_basic "input userAndpassword:";
 92         auth_basic_user_file "/usr/local/nginx/pass";
 93         location / {
 94             if ($request_filename ~* ^.*?\.(txt|pdf|doc|x    ls|png|jpg|jpeg)$){
 95                 add_header Content-Disposition "attachmen    t;";
 96             }
 97             root   /home/static;
 98             index  index.html index.htm;
 99         }
100     }

注意:配置完nginx需要生成密码文件,密码文件的生成同上一个实验,本实验不在赘述。

2、重载nginx,客户端验证

  • nginx重载:
nginx  -s  reload
  • 客户端验证:
  • 因为没有搭建DNS服务器,可以通过修改/etc/.hosts文件来实现ip地址解析:
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.4.5 www.a.com www.b.com

![image.png](https://img-blog.csdnimg.cn/img_convert/05043199cad266ec1febf1cd160130c2.png#averageHue=#f8f6f6&clientId=u070372fe-bdf3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u878fc911&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=82124&status=done&style=none&taskId=ua0cf74ae-a3eb-45f7-b681-2a60d6463a0&title=&width=1536.8)
注意:www.a.com和www.b.com都监听在80端口,但是两个web服务的网站根目录不一样。www.a.com的网站根目录在/home/static/。www.b.com的网站根目录在/usr/local/nginx/html/。如此,便实现了通过输入不同的域名来获得不同的web服务。
![image.png](https://img-blog.csdnimg.cn/img_convert/b478985d7a5bef5c9d519640e9d97b86.png#averageHue=#f8f6f6&clientId=uc5a02e06-0082-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=ud7ad8fc5&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=83002&status=done&style=none&taskId=u141aa280-a2f6-4707-8bcb-71c0e00bc28&title=&width=1536.8)

四、SSL加密网站

  1. 域名为www.c.com
  2. 该网站通过https访问
  3. 通过私钥,证书对该站点所有数据加密

1、修改nginx配置文件

  • nginx在源码安装的时候,需要安装–with-http_ssl_module模块。在nginx配置文件中需要添加ssl相关的指令来对网站进行加密。
  • 生成私钥和证书:(证书用来加密,私钥用来解密)
[root@proxy ~]# cd /usr/local/nginx/conf/
[root@proxy conf]# openssl genrsa > cert.key  //生成私钥,因为nginx配置文件中私钥默认放在/usr/local/nginx/conf下,所以,我们生成的私钥也放在这里。
Generating RSA private key, 2048 bit long modulus
..+++
...................+++
e is 65537 (0x10001)
[root@proxy conf]# openssl req -new -x509 -key cert.key > cert.pem  //基于私钥生成证书,生成证书的过程中会让你回答一些问题,这些问题可以随便回答。
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) []:HE^HN
Locality Name (eg, city) [Default City]:ZK
Organization Name (eg, company) [Default Company Ltd]:ZK
Organizational Unit Name (eg, section) []:ZK
Common Name (eg, your name or your server's hostname) []:HFSA^H
Email Address []:123456@163.COM^H^H
[root@proxy conf]# 

通过以上命令便在/usr/local/nginx/conf下生成了私钥(cert.key)和证书(cert.pem)。
![image.png](https://img-blog.csdnimg.cn/img_convert/7adba04c0ce5b01ab4940575d6a11b4d.png#averageHue=#fcfbfb&clientId=u836b823c-49dc-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=648&id=u176e0952&margin=[object Object]&name=image.png&originHeight=810&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=26561&status=done&style=none&taskId=u32cb167e-7a0f-45f8-b7be-7ee38d9ad24&title=&width=1536.8)

  • 修改nginx配置文件:
105     server {
106         listen       443 ssl;  //加密后的网站在443端口进行监听
107         server_name  www.c.com;
108 
109         ssl_certificate      cert.pem;
110         ssl_certificate_key  cert.key;
111 
112         ssl_session_cache    shared:SSL:1m;
113         ssl_session_timeout  5m;
114 
115         ssl_ciphers  HIGH:!aNULL:!MD5;
116         ssl_prefer_server_ciphers  on;
117 
118         location / {
119             root   /home/www;  //网站根目录变为了/home/www/,在浏览器输入https://www.c.com会将/home/www/目录下的index.html文件传送到浏览器显示
120             index  index.html index.htm;
121         }
122     }

2、重载nginx并在客户端验证

重载nginx:

nginx  -t
nginx  -s  reload

客户端验证:
![image.png](https://img-blog.csdnimg.cn/img_convert/9aa7a366ad7646691c3c5a84adae075c.png#averageHue=#919c9b&clientId=uf76d16df-350f-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u13477ee8&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=121359&status=done&style=none&taskId=ua7262661-7c84-4b9e-9276-bedb8dbe4fd&title=&width=1536.8)
![image.png](https://img-blog.csdnimg.cn/img_convert/0d6af365f433ce913276bbd617b4f549.png#averageHue=#f9f7f6&clientId=uf76d16df-350f-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=ufe81e5d8&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=92483&status=done&style=none&taskId=u0566e3bf-16da-4a43-bf90-6c692d98f61&title=&width=1536.8)

五、部署LNMP服务

LNMP实际上就是Linux、nginx、MySQL、PHP的简称。通过这四个服务,可以将一个完整的PHPweb项目上线。一个完整的PHPweb项目是需要动静分离的,即动态资源和静态资源分开,而LNMP环境可以实现动静分离。
LNMP实现效果:

  1. 如果用户访问的是静态资源,则到html目录寻找,直接返回。
  2. 如果用户访问的是动态脚本,则在html目录去找并交给PHP处理。

注:nginx监听在80端口,PHP监听在9000端口。

1、安装nginx、MySQL、PHP

  • nginx源码安装不在赘述。
  • 安装MySQL
yum -y install mariadb mariadb-server mariadb-devel
  • mariadb:数据库客户端软件
  • mariadb-server:数据库服务器软件
  • mariadb-devel:其它客户端软件的依赖包
  • 安装PHP
yum -y install php php-fpm php-mysql
  • php:解释器
  • php-fpm:PHP进程管理器服务
  • php-mysql:PHP的数据库扩展包

2、开启nginx、MySQL、PHP

[root@proxy ~]# systemctl start mariadb    //开启mariadb
[root@proxy ~]# systemctl enable mariadb   //将mriadb设置为开机自启
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@proxy ~]# systemctl start php-fpm    //开启php
[root@proxy ~]# systemctl enable php-fpm    //将php设置为开机自启
Created symlink from /etc/systemd/system/multi-user.target.wants/php-fpm.service to /usr/lib/systemd/system/php-fpm.service.
[root@proxy ~]# systemctl status mariadb    //查看mariadb运行状态
[root@proxy ~]# systemctl status php-fpm    //查看php运行状态
[root@proxy ~]# nginx    //开启nginx

3、修改nginx配置文件

 65         location ~ \.php$ {
 66             root           html;
 67             fastcgi_pass   127.0.0.1:9000;
 68             fastcgi_index  index.php;
 69            # fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
 70             include        fastcgi.conf;
 71         }

4、重载nginx并进行客户端验证

PHP测试文件:

<?php
$i="This is a test Page";
echo $i;
?>

测试结果如下:

![image.png](https://img-blog.csdnimg.cn/img_convert/acec595160960a1700f374b81c87c698.png#averageHue=#fefdfd&clientId=u39ad9763-9da3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=ucea45149&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=64894&status=done&style=none&taskId=u9abd6863-6c22-41fb-bfa8-b9efbfad7cf&title=&width=1536.8)
说明在获得test.php脚本的时候,在/usr/local/nginx/html中找到该文件,并将该文件交给php处理,并将处理结果返回到浏览器。否则,没有交给PHP处理的话,会得到PHP代码,但是,用户只想要PHP代码的处理结果。

PHP和MySQL结合:

<?php
$mysqli = new mysqli('localhost','root','','mysql');	//localhost为连接本地的MySQL数据库,root:表示用root用户连接,''':表示密码为空,MySQL:表示连接好数据库,进入名为mysql的数据库中。
if (mysqli_connect_errno()){
        die('Unable to connect!'). mysqli_connect_error();
}
$sql = "select * from user";
$result = $mysqli->query($sql);
while($row = $result->fetch_array()){
        printf("Host:%s",$row[0]);
        printf("</br>");
        printf("Name:%s",$row[1]);
        printf("</br>");
}
?>

测试结果如下:

![image.png](https://img-blog.csdnimg.cn/img_convert/ff927911637f7e451dd044e1fc06277f.png#averageHue=#fefcfc&clientId=u8b76a2a7-7696-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=ue706e407&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=76772&status=done&style=none&taskId=u2eab2c89-465a-4dba-bf46-001df657101&title=&width=1536.8)
PHP和mysql成功连接,并获得了MySQL中MySQL数据库中的user表中的数据。

添加MySQL用户,查看浏览器端是否动态变化

命令行输入mysql,进入mysql中。然后输入下行代码添加一个lisa用户密码为123
grant all on *.* to 'lisa'@'localhost' identified by '123';
grant all on *.* to 'hali'@'localhost' identified by '789';  //添加一个hali用户密码为789

测试结果:

![image.png](https://img-blog.csdnimg.cn/img_convert/548dd0f65a022345bf371335aaf66e3a.png#averageHue=#fefcfc&clientId=u66ea69b5-c5f4-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u78f4be36&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=88301&status=done&style=none&taskId=ue10aea6f-5673-4db7-90c3-551e933638a&title=&width=1536.8)

LNMP环境部署脚本

#!/bin/bash
#安装nginx
path=/usr/local/nginx/conf
tar -xf nginx-1.12.2.tar.gz
cd nginx-1.12.2
./configure
make && make install
cp /usr/local/nginx/sbin/nginx /usr/local/sbin/
nginx -V
echo "nginx安装成功"
#安装mariadb mariadb-server mariadb-devel
#安装php php-fpm php-myql
yum -y install mariadb mariadb-server mariadb-devel
yum -y install php php-fpm php-myql
#修改nginx的配置文件,实现动静分离
sed -i '65,71s/#//' $path/nginx.conf
sed -i '/SCRIPT_FILENAM/d' $path/nginx.conf
sed -i 's/fastcgi_params/fastcgi.conf/' $path/nginx.conf
systemctl start mariadb
systemctl enable mariadb
systemctl start php-fpm
systemctl enable php-fpm
nginx

六、地址重写

  1. 所有访问a.html的请求,重定向到b.html
  2. 所有访问192.168.4.5的请求重定向到www.tmooc.cn
  3. 所有访问192.168.4.5/下面的子页面,重定向到www.tmooc.cn/下相同的页面
  4. 实现firefox与curl访问相同页面文件,返回不同的内容

解决方案

  • nginx服务器的地址重写,主要用到的配置参数是rewrite:
  • rewrite 旧地址 新地址 [选项]

6.1

35     server {
 36         listen       80;
 37         server_name  localhost;
 38         rewrite /a.html /b.html;  //要实现地址重定向只需要添加该行代码即可
 39 
 40         #charset koi8-r;
 41 
 42         #access_log  logs/host.access.log  main;
 43 
 44         location / {
 45             root   html;
 46             index  index.html index.htm;
 47         }
			}

注:/a.html中的/,指网站根目录。本次实验使用的是默认的web服务,所以网站根目录为/usr/local/nginx/html/。

客户端验证

![image.png](https://img-blog.csdnimg.cn/img_convert/b1e222c3e855f1da049fecb029b51399.png#averageHue=#fcfafa&clientId=uf37e8b5e-d1ff-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=ua24eb978&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=74492&status=done&style=none&taskId=u7e6e0e10-22a6-44e4-b449-f798bbb2d2e&title=&width=1536.8)
可以看到地址栏仍是192.168.4.5/a.html,要想地址栏变为192.168.4.5/b.html需要在nginx.conf中加上如下代码:

 rewrite /a.html /b.html redirect;

6.2

 35     server {
 36         listen       80;
 37         server_name  localhost;
 38         rewrite ^/ http://www.tmooc.cn/; //主要是这行代码起作用
 39         #charset koi8-r;
 40 
 41         #access_log  logs/host.access.log  main;
 42 
 43         location / {
 44             root   html;
 45             index  index.html index.htm;
 46         }
		}

要想输入一个网址跳转到其它网址,将localhost修改为网址即可。例如将localhost修改为https://www.hfs.com便会跳转到http://www.tmooc.cn/。
实验简单,不在做验证

6.3

35     server {
 36         listen       80;
 37         server_name  localhost;
 38         rewrite ^/(.*) http://www.tmooc.cn/$1$2;
 39         #charset koi8-r;
 40 
 41         #access_log  logs/host.access.log  main;
 42 
 43         location / {
 44             root   html;
 45             index  index.html index.htm;
 46         }
		}
  • nginx中$1就相当于正则表达式中的\1,意思是将()中的内容复制到http://www.tmooc.cn/$1处,因为()中是(.*)两个字符。所以,是$1和$2。
  • ()在正则表达式中是保留的意思,可以通过\1、\2来复制()中保留的字符。

客户端验证

![image.png](https://img-blog.csdnimg.cn/img_convert/8ec8ee1cd878d1a651945fd9ffec4587.png#averageHue=#86bcb4&clientId=uf37e8b5e-d1ff-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u1b1a8cbe&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=825114&status=done&style=none&taskId=ucf01d64e-4704-4ccc-962c-78f03e58f74&title=&width=1536.8)
浏览器地址栏输入,192.168.4.5/free,跳转到https://www.tmooc.cn/free

6.4

本次实验的实验效果是,curl和火狐浏览器访问相同链接返回的页面不同。这种方式的应用场景适合不同客户端给予不同的访问结果。例如:手机访问www.sina.com是窄屏的,电脑访问www.sina.com是宽屏的。

补充:nginx中access.log日志中各字段的含义

192.168.4.1 - - [27/Dec/2022:15:25:03 +0800] "GET /vip HTTP/1.1" 302 161 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"

21     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 22     #                  '$status $body_bytes_sent "$http_referer" '
 23     #                  '"$http_user_agent" "$http_x_forwarded_for"';

$remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for
ip地址的来源 日志文件中就是一个"-"
访问的时间 包括访问的类型,是get请求还是post请求,访问的协议是什么协议。 访问状态码,如果访问成功就是200,如果没有找到要访问的资源,就是404。 资源的大小,即有多少个字节,返回给访问者。 访问来源,即如果是通过百度搜索一个网站,点击而来。这里显示百度。如果是通过输入域名直接访问,这里什么也没有。 包括访问者用的什么系统,用的什么版本的浏览器。
192.168.4.1 - - [27/Dec/2022:15:25:03 +0800] “GET /vip HTTP/1.1” 302 161 “-” “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36”

创建测试页面

echo "i am normal page" > /usr/local/nginx/html/test.html
mkdir -p /usr/local/nginx/html/firefox/
echo "firefox page" > /usr/local/nginx/html/firefox/test.html

修改nginx配置文件

 35     server {
 36         listen       80;
 37         server_name  localhost;
 38         #charset koi8-r;
 39 
 40         #access_log  logs/host.access.log  main;
 41         if ($http_user_agent ~* firefox){
 42             rewrite ^/(.*) /firefox/$1$2;
 43         }
 44         location / {
 45             root   html;
 46             index  index.html index.htm;
 47         }
		}
 41         if ($http_user_agent ~* firefox){
 42             rewrite ^/(.*) /firefox/$1$2;
 43         }

通过上面的日志文件,我们可以知道,$http_user_agent列会显示用户使用的什么浏览器来进行访问的。

  • ~:进行正则匹配,正则匹配包含即可。
  • *:不区分大小写

41到43行代码的含义是,如果地址栏输入192.168.4.5/test.html之后,如果在日志文件中显示是Firefox浏览器,就地址重定向到/usr/local/nginx/firefox/下去找test.html。

客户端验证

![image.png](https://img-blog.csdnimg.cn/img_convert/b46b2f5388f500d6dded9c03788b1848.png#averageHue=#fcfbfb&clientId=uf37e8b5e-d1ff-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u03949b03&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=60730&status=done&style=none&taskId=u36081205-93d1-4ad0-b518-57683de50df&title=&width=1536.8)
![image.png](https://img-blog.csdnimg.cn/img_convert/6590c3c72c8eb8639844090d5ef381e9.png#averageHue=#f9f8f7&clientId=uf37e8b5e-d1ff-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=uae9803be&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=77439&status=done&style=none&taskId=u5a914be1-1410-40c3-bac3-ad61cbdf65e&title=&width=1536.8)

地址重写总结

  • rewrite 旧地址 新地址 [选项];
  • last 不再读其他rewrite
  • break 不再读其他语句,结束请求
  • redirect 临时重定向
  • permanent 永久重定向

七、nginx反向代理(nginx做代理服务器)

  • 在做服务器集群的时候,可以使用nginx做代理服务器。或者说称之为调度器。
  • nginx做代理服务器,部署不同的服务器集群,需要安装不同的模块,这些模块需要在nginx源码编译的时候,进行添加。

1、实验拓扑图

2、web1和web2构建web服务

yum -y install httpd
echo "192.168.2.100" > /var/www/html/index.html
systemctl start httpd
systemctl enable httpd
firewall-cmd --set-default-zone=trusted
setenforce 0

注:web1和web2部署相同的服务。只有部署相同的服务才能做服务器集群,但是实验过程中为了方便验证,可以让index.html不同。这样方便客户端验证。

3、修改nginx配置文件

    upstream webserver {
        server 192.168.2.100:80;  //这些是服务器集群的机器的IP地址
        server 192.168.2.200:80;
      }
    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        
        #access_log  logs/host.access.log  main;
        location / {
            proxy_pass http://webserver;  //表示将请求转发到webserver这个服务器集群处理
            root   html;
            index  index.html index.htm;
        }
}

注意:upstream是写在server外面,http里面的。因为nginx是做http服务调度器。所以,要写在http里面。

4、nginx重载并在客户端验证

nginx重载不在赘述,前面实验修改完配置文件都需要重载。已经练习很多次了。
客户端验证:
![image.png](https://img-blog.csdnimg.cn/img_convert/f94d8118197fb7c43f52b35cef2cb795.png#averageHue=#2a3b48&clientId=ud550ed7f-079a-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=ua6133797&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=1527741&status=done&style=none&taskId=u4fe6350f-887c-481d-9637-23af4fe36e6&title=&width=1536.8)
![image.png](https://img-blog.csdnimg.cn/img_convert/8506203a4a21ce6861d545bf66f522dd.png#averageHue=#f5f4f4&clientId=ud550ed7f-079a-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=832&id=u78438e75&margin=[object Object]&name=image.png&originHeight=1040&originWidth=1921&originalType=binary&ratio=1&rotation=0&showTitle=false&size=392706&status=done&style=none&taskId=ub656116d-796d-472e-afc9-6f0c80780ca&title=&width=1536.8)
可以看到nginx将请求转发给了webserver那个服务器集群处理了,为了实验方便我们在/var/www/html下放置了不同的index.html文件。
注:nginx默认使用的是轮询算法,即请求交替转发到集群中的每一台机器上。

八、nginx做TCP/UDP调度器

  • nginx做TCP/UDP调度器,编译时需要使用–with-stream,开启nginx_stream_core_module模块。
  • nginx如果开启了该模块,就可以调度一切服务,比如:做ssh服务器集群,做MySQL集群等等。

本次实验是做ssh服务器集群,而ssh功能是默认开启的。所以,web1和web2可以先不用管。主要是对proxy做配置即可。

1、修改nginx配置文件

 12 events {
 13     worker_connections  1024;
 14 }
 15 stream {
 16         upstream backend {
 17                 server 192.168.2.100:22;
 18                 server 192.168.2.200:22;
 19         }
 20         server {
 21                 listen 12345;  //proxy服务器在12345端口提供ssh集群服务。本来应该是在22端口的,但是proxy本身又有ssh服务,该服务在22端口提供。所以,需要定义一个非22端口来提供ssh集群。
 22                 proxy_pass backend;  //将请求转发到backend这个ssh服务集群
 23         }
 24 }
 25 
 26 http {
 27     include       mime.types;
 28     default_type  application/octet-stream;

因为ssh服务不属于http服务,所以写在http外面。

2、客户端验证

![image.png](https://img-blog.csdnimg.cn/img_convert/91baa5d4388c681b9c02c75aa472b35b.png#averageHue=#242121&clientId=ud550ed7f-079a-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=518&id=u32a68a8c&margin=[object Object]&name=image.png&originHeight=648&originWidth=1240&originalType=binary&ratio=1&rotation=0&showTitle=false&size=61197&status=done&style=none&taskId=u1c5c2644-4a2c-49d3-ab44-2b561c75977&title=&width=992)
![image.png](https://img-blog.csdnimg.cn/img_convert/62749ec1a391e56d1c9a79a90ee3819a.png#averageHue=#242121&clientId=ud550ed7f-079a-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=518&id=u58c58814&margin=[object Object]&name=image.png&originHeight=648&originWidth=1240&originalType=binary&ratio=1&rotation=0&showTitle=false&size=72492&status=done&style=none&taskId=u84d36459-5c7f-4ebb-ba0a-bd4bea88c27&title=&width=992)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用nginx搭建的各种服务 的相关文章

  • Websocket-rails 不适用于 Nginx 和 Unicorn 的生产环境

    我有 Rails 3 2 应用程序和 gem websocket rails 0 7 在开发机器上 一切正常 在生产环境中 我使用 Nginx 1 6 作为代理服务器 使用 Unicorn 作为 http 服务器 Thin 用于独立模式 如
  • Docker-compose Predis 不通过 PHP 连接

    我正在尝试使用 docker compose 将 PHP 与 redis 连接 docker compose yml version 2 services redis image redis 3 2 2 php image company
  • 如何在Python中在后台运行长时间运行的作业

    我有一个运行长时间运行的作业 大约几个小时 的网络服务 我正在使用 Flask Gunicorn 和 nginx 来开发它 我想做的是让需要很长时间才能完成的路线 调用创建线程的函数 然后 该函数将向路由返回一个 guid 并且路由将返回一
  • uWSGI重启时停机

    每次当我有代码更新时重新启动服务器时 我都会遇到 uwsgi 问题 当我使用 sudo restart account 重新启动 uwsgi 时 停止和启动实例之间存在一个小间隙 导致停机并停止所有当前请求 当我尝试 sudo reload
  • NGINX 与 Tomcat 配置

    我是 Nginx 新手 我需要你的帮助 根据很多论坛我了解到我们所有的静态页面都存储在Nginx中 当有请求到来时 我必须将该请求传递给 tomcat 获取数据 并在 tomcat 生成响应后生成响应 目前 我刚刚做到了 我将请求直接传递给
  • Node + Express + Nginx 未设置 Cookie

    我有一个使用 Express 的 Node 应用程序 我尝试为我的客户端设置 cookie 它在本地环境 http 上运行良好 但是一旦我投入生产 https 我就很好地收到了cookie 我可以在响应中看到它 但它没有设置 任何想法 Ng
  • 如果我在不打算升级到 websocket 连接的 HTTP 请求中包含“Upgrade”和“Connection”标头,会发生什么情况?

    我有一个 Nginx 服务器块 用于代理对 node js 服务器的请求 该服务器同时提供 HTTP 内容和 WS websocket 内容 是否可以在不应升级到 Websocket 连接的请求上添加升级标头 即使用 Nginx 代理到服务
  • 我怎样才能重写这个nginx“if”语句?

    例如 我想这样做 if http user agent MSIE 6 0 http user agent MSIE 7 0 etc etc rewrite ROOT ROOT ancient last break 而不是这个 if http
  • 使用 FastCGI 运行 Lua 脚本

    我目前正在尝试找出使用 FastCGI 与 lighttpd 或 Nginx 一起运行 Lua 脚本的方法 我唯一能挖到的是WSAPI http keplerproject github com wsapi 开普勒计划的一部分 但我想知道是
  • nginx 反向代理 websocket

    nginx 现在支持代理 websockets 但我无法找到任何有关如何在没有单独的情况下执行此操作的信息location应用于使用 websocket 的 URI 的块 我见过一些人推荐这种方法的一些变体 location proxy h
  • 如何正确链接 php-fpm 和 Nginx Docker 容器?

    我正在尝试链接 2 个单独的容器 nginx 最新 https registry hub docker com nginx php fpm https registry hub docker com php 问题是 php 脚本不起作用 也
  • 如何在运行 NGINX Docker 容器的 AWS EC2 上启用 HTTPS?

    我在 AWS 上有一个运行 Amazon Linux 2 的 EC2 实例 在上面 我安装了 Git docker 和 docker compose 完成后 我克隆了我的存储库并运行docker compose up让我的生产环境启动 我访
  • 我可以在 Nginx Conf 中添加多少个服务器块

    知道我可以在 Nginx 配置中添加多少个服务器块吗 我需要将它用于具有多个子域的反向代理 每个客户端一个子域 它能成功支持 10 000 个服务器块吗 有没有相关的基准研究 这实际上并不是一个你有多少人的问题can但你有多少 能够妥善处理
  • 找不到 NGINX brew 安装命令

    I do brew install nginx and get gt Downloading http nginx org download nginx 1 2 2 tar gz Already downloaded Library Cac
  • 将应用程序级别用户名/用户 ID 注入 nginx/Apache 日志

    有没有办法将应用程序级别的用户名或 id 在本例中为 django 用户名或 id 注入 Apache 或 ngnix 日志中 请注意 我不是询问 HTTP 身份验证用户名 我目前正在使用一个简短的自定义中间件将此数据添加到响应标头 如下所
  • nginx 和 uwsgi 非常大的文件上传(>3Gb)

    也许有人知道该怎么做 我正在尝试上传大于 3Gb 的文件 没问题 如果我使用以下配置上传高达 2Gb 的文件 Nginx client max body size 5g client body in file only clean clie
  • 常规请求期间 Django AJAX 请求未通过

    我有一个带有登录网页的 Django 站点 当提交页面上的登录表单时 它会执行登录视图 该视图会在其中运行一个需要很长时间处理 30秒左右 的函数 因此 为了在登录期间向客户端显示进度 一旦提交表单 登录页面上的 JS 函数就会开始向服务器
  • 使用nginx容器作为反向代理时的原始url

    我有一个 Web 应用程序部署为码头集装箱 我也有一个nginx容器 使用dnsmasq解析器 设置为充当 Web 应用程序前面的反向代理 它的 80 端口映射到主机 我的应用程序使用 SSO 身份验证 当我使用身份提供商登录时 回调 ur
  • Beanstalk 部署忽略 .ebextensions 中的 nginx 配置文件

    我在单实例 Elastic Beanstalk 环境中托管 Java Web 应用程序 并添加了几个 ebextension 文件 这些文件在每次部署时成功为我创建配置文件 然而 我无法找到一种方法让 Beanstalk 在 etc ngi
  • Rails/Nginx 中的超时——最佳实践

    我正在开发一个应该在 Nginx 服务器上运行的 Rails 应用程序 根据输入 应用程序可能需要很长时间来处理请求 或者在出现错误时挂起 因此我想防止进程永远运行 除了确保客户端收到超时信号的 Nginx 配置之外 我想我可能仍然需要确保

随机推荐

  • 数字图像直方图处理涉及的数学知识介绍

    前往老猿Python博文目录 https blog csdn net LaoYuanPython 一 引言 在数字图像直方图处理学习时 老猿发现相关内容涉及数学定积分 概率统计等相关的知识 为此专门投入2个月时间将忘光了导数 微分 不定积分
  • ACN总结报告

    ACM总结报告 关于学到的知识 先暂且留一下 先说说这学期的情况 还记得 刚开始时选择这门选修课 除了听说它对于我们计算机专业的来说很有用之外 就是听说它很难 想要挑战一下自我而已 想想 现在不由自主的想要笑起来 说实在的 对于这门选修课
  • Flamingo插件_Contact Form 7表单数据存储插件

    Flamingo插件是一款用来帮助 Contact Form 7表单数据存储的插件 因为Contact Form 7插件本身没有数据存储功能 默认把前台访客提交的表单数据提交到设置好的接收邮箱 如果邮件服务器出现问题 配置错误就可能会永远丢
  • 第一课:一文读懂马尔科夫过程

    1 马尔科夫决策过程 MDPs 简介 马尔科夫决策过程是对强化学习 RL 问题的数学描述 几乎所有的RL问题都能通过MDPs来描述 最优控制问题可以用MDPs来描述 部分观测环境可以转化成POMDPs 赌博机问题是只有一个状态的MDPs 注
  • 查看LINUX放开端口,Linux下防火墙开启相关端口及查看已开启端口

    Linux下防火墙开启相关端口及查看已开启端口 1 默认情况下Linux的防火墙都是在关闭状态下的 root test etc service iptables status Firewall is stopped root test et
  • 新建Springboot项目默认test包下的测试类报错缺少org.junit.jupiter.api

    在springboot项目中碰到一个问题 记录一下 新建了一个普通的Maven项目A 其pom xml继承parent为
  • 电脑怎么恢复已删除的数据?

    恢复已经删除的数据取决于多种因素 包括删除的方式 存储设备的类型以及是否有备份等 以下是一些常见的方法 但不能保证所有情况下都能成功恢复数据 在尝试恢复数据之前 请确保不会进一步覆盖原始数据 以提高恢复成功的机会 回收站 如果你删除的是电脑
  • mysql数据去重并排序使用distinct 和 order by 的问题

    比如直接使用 SELECT distinct mobileFROM table aWHERE code 123ORDER BY a ime desc 在本地mysql数据库没有错 在线上的数据库就会报如下错 估计是版本的问题 Express
  • 典型的贪心算法~ (田忌赛马 )

    1 田忌赛马 典型的贪心算法 自己木有考虑到贪心的第二步导致wa了好多次 算法分析 Problem Description 给出2N组数据 分别表示田忌和齐威王的N匹马的速度 没进行一场比赛 每组数据共N场场赛 若能分出胜负 则输的一方要给
  • DVWA之SQL注入

    一 DVWA介绍 1 1 DVWA简介 DVWA是一款基于PHP和MYSQL开发的web靶场练习平台 集成了常见的web漏洞如sql注入 XSS 密码破解等常见漏洞 旨在为安全专业人员测试自己的专业技能和工具提供合法的环境 帮助web开发者
  • 七牛云上传图片,只需十分钟搞定

    1 去七牛云注册 建好自有空间 2 导入依赖
  • Sonar常见问题解决方案

    阻断 1 Close this FileInputStream in a finally clause 在finally中关闭FileInputStream 这个最为常见 主要是关闭方式不对 finally代码块中 应该要对每个stream
  • FCGI

    fcgi作为客户端需要注意的几点 http blog csdn net cleanfield article details 6699952 fcgi作为中间层 需要与后端server通信进行数据处理 这里需要注意一下几点 1 要做好超时处
  • 日历插件可选择_Obsidian——推荐插件

    Obsidian 推荐插件 工具 Obsidian 官方插件 关系图谱 页面预览 预览模式中 鼠标悬浮于一个内链时 显示小窗预览 编辑模式中 鼠标悬浮于链接上的同时按住 Ctrl Cmd 也会显示预览小窗 快速切换 Ctrl Cmd O 在
  • 开山之作,简单说说什么是"集群(Cluster)"

    一 什么是集群 集群 Cluster 是由两台或多台节点机 服务器 构成的一种松散耦合的计算节点集合 为用户提 供网络服务或应用程序 包括数据库 Web服务和文件服务等 的单一客户视图 同时提供接近容错机的故 障恢复能力 集群系统一般通过两
  • AndroidStudio项目打包成library以及jar包、aar包流程

    引言 一般项目做多了后 码农们都会整理出一系列的工具类来 为了方便在后面项目中使用 打包成library或者jar aar包供项目使用是比较好的方式 1 library方式 library方式是比较简单的方式 一般新建完一个项目的时候 点击
  • mysql意向锁的概念和用途

    锁的粒度 A 表锁 Table Lock 对整个表加锁 影响标准的所有记录 通常用在DDL语句中 如DELETE TABLE ALTER TABLE等 B 行锁 Row Lock 对一行记录加锁 只影响一条记录 通常用在DML语句中 如IN
  • Visio如何插入公式、MathTape安装

    遇到的问题 在写论文过程中发现Visio没有插入公式的选项 而从word中复制过来邮无法识别 经过我在一番百度以后解决了这个问题 首先要求我们的电脑上已经装好WPS或者MathType 我的电脑已经装了office 所以不想再装WPS 所以
  • 课程计划、课程标准、教材三者关系

    课程主要表现为课程计划 课程标准 教材 教科书是其主要部分 课程计划 国家教育主管部门制定的 包括课程设置 学科顺序 课时分配 学年编制和学周安排 课程标准 国家根据课程计划纲要的形式编写的有关某门学科的内容及实施 评价的指导行文件 如 高
  • 使用nginx搭建的各种服务

    一 nginx搭建文件服务器 1 安装nginx bin bash 安装nginx的脚本文件 先按照nginx的依赖 yum y install gcc openssl devel pcre devel gt dev null echo n