当前位置: 首页 > article >正文

详细Linux中级知识(不断完善)

Nginx服务配置

基于主机名配置

映射IP和主机名

[root@localhost ~]# vim /etc/hosts
192.168.72.135  www.chengke.com chengke


[root@localhost ~]# echo "192.168.72.135 www.xx.com" >> /etc/hosts

以上是两种方法,前面是你的IP地址,后面是你想要设置的域名

安装Nginx

1、查看nginx是否已经安装

[root@localhost ~]# rpm -ql nginx
package nginx is not installed

这表示没有安装。

2、查看是否有仓库配置

[root@localhost ~]# dnf repolist
repo id                                           repo name
appStream                                         AppStream
baseOS                                            BaseOS

编写仓库基础知识文字里有
 

3、查看是否挂载

[root@localhost ~]# ls /mnt
hgfs
[root@localhost ~]# mount /dev/sr0 /mnt
mount: /mnt: WARNING: source write-protected, mounted read-only.
[root@localhost ~]# ls /mnt
AppStream  EFI   extra_files.json  images    media.repo               RPM-GPG-KEY-redhat-release
BaseOS     EULA  GPL               isolinux  RPM-GPG-KEY-redhat-beta

这是红帽的,根据版本的问题,有些自动挂载,有些需要手动挂载。

4、安装nginx

[root@localhost ~]# dnf install nginx -y
BaseOS                                                              847 kB/s | 2.7 kB     00:00    
AppStream                                                           3.1 MB/s | 3.2 kB     00:00    
Dependencies resolved.
====================================================================================================
 Package                      Architecture     Version                    Repository           Size
====================================================================================================
Installing:
 nginx                        x86_64           2:1.20.1-20.el9            appStream            40 k
Installing dependencies:
 nginx-core                   x86_64           2:1.20.1-20.el9            appStream           574 k
 nginx-filesystem             noarch           2:1.20.1-20.el9            appStream            11 k
 redhat-logos-httpd           noarch           90.4-2.el9                 appStream            18 k
​
Transaction Summary
====================================================================================================
Install  4 Packages
​
Total size: 643 k
Installed size: 1.8 M
Downloading Packages:
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                            1/1 
  Running scriptlet: nginx-filesystem-2:1.20.1-20.el9.noarch                                    1/4 
  Installing       : nginx-filesystem-2:1.20.1-20.el9.noarch                                    1/4 
  Installing       : nginx-core-2:1.20.1-20.el9.x86_64                                          2/4 
  Installing       : redhat-logos-httpd-90.4-2.el9.noarch                                       3/4 
  Installing       : nginx-2:1.20.1-20.el9.x86_64                                               4/4 
  Running scriptlet: nginx-2:1.20.1-20.el9.x86_64                                               4/4 
  Verifying        : nginx-2:1.20.1-20.el9.x86_64                                               1/4 
  Verifying        : nginx-core-2:1.20.1-20.el9.x86_64                                          2/4 
  Verifying        : nginx-filesystem-2:1.20.1-20.el9.noarch                                    3/4 
  Verifying        : redhat-logos-httpd-90.4-2.el9.noarch                                       4/4 
Installed products updated.
​
Installed:
  nginx-2:1.20.1-20.el9.x86_64                       nginx-core-2:1.20.1-20.el9.x86_64              
  nginx-filesystem-2:1.20.1-20.el9.noarch            redhat-logos-httpd-90.4-2.el9.noarch           
​
Complete!

配置ngnix

我们在 /etc/nginx/conf.d/ 目录下创建我们自己的自定义配置文件。

[root@localhost ~]# vim /etc/nginx/conf.d/chengke.conf
server {
        listen  80;
        server_name     www.chengke.com;
        access_log      /var/log/nginx/chengke/access.log;
        error_log       /var/log/nginx/chengke/error.log;
        root    /opt/chengke;
}

1. [root@localhost ~]# vim /etc/nginx/conf.d/chengke.conf
这并非 Nginx 配置文件的内容,而是一条在 Linux 系统中使用vim编辑器来打开 /etc/nginx/conf.d/chengke.conf 文件的命令。

2. server {
此行为一个server块的起始,在 Nginx 里,server块用来定义虚拟主机,能够对不同的域名或者 IP 地址设置不同的配置。

3. listen 80;
这行代码告知 Nginx 要监听 80 端口,也就是 HTTP 协议的默认端口。当有客户端发起 HTTP 请求时,Nginx 会接收这些请求并进行处理。

4. server_name www.chengke.com;
该配置指定了这个虚拟主机所对应的域名。当客户端通过www.chengke.com这个域名发起请求时,Nginx 会采用这个server块的配置来处理请求。

5. access_log /var/log/nginx/chengke/access.log;
此配置指定了访问日志的存放路径。Nginx 会把所有针对这个虚拟主机的访问记录保存到 /var/log/nginx/chengke/access.log 文件中,这些记录有助于后续分析用户的访问行为。

6. error_log /var/log/nginx/chengke/error.log;
这行代码指定了错误日志的存放路径。当 Nginx 在处理请求过程中出现错误时,相关的错误信息会被记录到 /var/log/nginx/chengke/error.log 文件中,这有助于排查问题。

7. root /opt/chengke;
此配置定义了这个虚拟主机的根目录。当客户端请求静态文件时,Nginx 会从 /opt/chengke 目录下查找对应的文件。

综上所述,这段配置文件的作用是创建一个虚拟主机,监听 80 端口,对应域名www.chengke.com,并将访问日志和错误日志分别记录到指定文件,同时将 /opt/chengke 目录作为根目录来提供静态文件服务。

然后创建配置文件所需要的目录。

[root@localhost ~]# mkdir /opt/chengke -p
[root@localhost ~]# mkdir /var/log/nginx/chengke -p

具体的文件会根据配置自动创建,但是目录需要手动创建

启动服务

[root@localhost ~]# systemctl start nginx
[root@localhost ~]# ps -ef | grep nginx
root       12510       1  0 14:53 ?        00:00:00 nginx: master process /usr/sbin/nginx
nginx      12511   12510  0 14:53 ?        00:00:00 nginx: worker process
nginx      12512   12510  0 14:53 ?        00:00:00 nginx: worker process
nginx      12513   12510  0 14:53 ?        00:00:00 nginx: worker process
nginx      12514   12510  0 14:53 ?        00:00:00 nginx: worker process
root       12516    1112  0 14:53 pts/0    00:00:00 grep --color=auto nginx


主播认为出现的问题:
Nginx 配置未生效或错误:虽然你在 /etc/nginx/conf.d/chengke.conf 中配置了针对 www.chengke.com 的虚拟主机,但是 Nginx 可能没有正确加载该配置。可能的原因包括:
配置文件语法错误:你可以使用 nginx -t 命令来检查 Nginx 配置文件的语法是否正确。如果存在语法错误,Nginx 不会重新加载配置,仍然会使用之前的配置或默认配置。
[root@localhost ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
这样表示没错,否则会提示具体行数。(新手可能性大)

配置文件未被加载:确认 Nginx 主配置文件(/etc/nginx/nginx.conf)中是否包含了 include /etc/nginx/conf.d/*.conf; 这样的语句,以便让 Nginx 加载 /etc/nginx/conf.d/ 目录下的所有配置文件。

Nginx 服务未重启或重新加载配置:修改配置文件后,需要执行 systemctl restart nginx 或 systemctl reload nginx 命令使配置生效。如果没有执行这些操作,Nginx 仍会使用旧的配置。
域名解析问题:确保 www.chengke.com 正确解析到了当前运行 Nginx 服务器的 IP 地址。你可以通过 ping www.chengke.com 命令来检查域名解析是否正常。如果域名解析不正确,你访问的可能并不是你配置的 Nginx 服务器。

根目录内容缺失:你在配置文件中设置了 root /opt/chengke;,但 /opt/chengke 目录下可能没有放置任何内容,或者没有正确的索引文件(如 index.html)。在这种情况下,Nginx 可能会回退到默认的行为,展示 Red Hat Enterprise Linux 的测试页面。

存在其他默认配置优先:Nginx 可能还有其他默认的虚拟主机配置,这些配置可能会优先于你设置的 www.chengke.com 配置。例如,在 Nginx 的默认配置中可能已经定义了一个监听 80 端口的默认虚拟主机,当请求无法匹配到具体的虚拟主机时,就会展示默认的测试页面。默认的测试界面就是一个html文件的代码。

有其他进程占用了80端口,解决方法如下:都可以尝试查询错误日志
[root@localhost ~]# tail -n 50 /var/log/nginx/error.log
2025/03/24 16:19:35 [emerg] 38144#38144: bind() to 0.0.0.0:80 failed (98: Address already in use)
2025/03/24 16:19:35 [emerg] 38144#38144: bind() to [::]:80 failed (98: Address already in use)
2025/03/24 16:19:35 [emerg] 38144#38144: bind() to 0.0.0.0:80 failed (98: Address already in use)
2025/03/24 16:19:35 [emerg] 38144#38144: bind() to [::]:80 failed (98: Address already in use)
2025/03/24 16:19:35 [emerg] 38144#38144: bind() to 0.0.0.0:80 failed (98: Address already in use)
2025/03/24 16:19:35 [emerg] 38144#38144: bind() to [::]:80 failed (98: Address already in use)
部分
查找占用 80 端口的进程:在 Linux 系统中,使用lsof或netstat命令查找占用 80 端口的进程。以lsof为例,执行lsof -i :80 ,该命令会列出所有打开 80 端口的进程信息,包括进程 ID(PID)、进程名等。若使用netstat,则执行netstat -tulnp | grep :80,-t表示 TCP 协议,-u表示 UDP 协议,-l表示仅列出监听状态的端口,-n表示不解析服务名,直接显示端口号,-p表示显示占用端口的进程 ID 和进程名。

停止占用端口的进程:如果查找到占用 80 端口的进程是不必要的服务,如 Apache(若已安装且未使用),可以停止该进程。若使用systemctl管理服务,对于 Apache 服务,执行sudo systemctl stop httpd(CentOS/RHEL 系统)或sudo systemctl stop apache2(Debian/Ubuntu 系统)。若占用进程是其他未知程序,且不清楚其作用,不要随意停止,先确认其功能,避免影响系统正常运行。

修改 Nginx 监听端口:如果不想停止占用 80 端口的进程,或者无法确定该进程是否可停止,可以修改 Nginx 的监听端口。打开 Nginx 配置文件,一般在/etc/nginx/nginx.conf或/etc/nginx/conf.d/目录下的相关配置文件中,找到类似listen 80;的配置行,将其修改为其他未被占用的端口,如listen 8080; ,保存文件后,重新加载 Nginx 配置使修改生效,执行sudo systemctl reload nginx 。修改端口后,访问网站时需使用新的端口号,如http://your_domain:8080。
 
简单来说就是要么修改你的端口号,要么停止80端口的服务,比如httpd。



功能测试

1、使用 curl 命令

[root@localhost ~]# curl www.chengke.com
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

这个错误是因为中默认情况下会显示服务的根目录(/opt/chengke/)下的 index.html 文件,因此,我们需要先创建这个文件,简单来说我们打开一个网页,需要有一个html文件进行显示,但是现在没有展示的东西。

[root@localhost ~]# echo "chengke index.html" > /opt/chengke/index.html
​
# 创建好后,再次访问就可以成功了。
[root@localhost ~]# curl www.chengke.com
chengke index.html

几个指令介绍

root 指令

我们修改 /etc/nginx/conf.d/chengke.conf 配置文件

[root@localhost ~]# vim /etc/nginx/conf.d/chengke.conf
server {
        listen  80;
        server_name     www.chengke.com;
        access_log      /var/log/nginx/chengke/access.log;
        error_log       /var/log/nginx/chengke/error.log;
        location / {
                root    /opt/chengke;
                index   index.html;
        }
}
​
[root@localhost ~]# systemctl restart nginx
[root@localhost ~]# curl www.chengke.com
chengke index.html

初始 root 指令配置:在最初的 /etc/nginx/conf.d/chengke.conf 配置文件中,使用了 root 指令来指定网站的根目录。对于 location / 这个配置块,root /opt/chengke; 意味着当用户访问根路径(如 www.chengke.com)时,Nginx 会从 /opt/chengke 目录下寻找资源,index index.html; 表示优先寻找 index.html 文件。当执行 curl www.chengke.com 时,返回 chengke index.html,说明 Nginx 成功从指定目录读取并返回了文件内容。
alias 指令
# 修改配置文件
[root@localhost ~]# vim /etc/nginx/conf.d/chengke.conf
server {
        listen  80;
        server_name     www.chengke.com;
        access_log      /var/log/nginx/chengke/access.log;
        error_log       /var/log/nginx/chengke/error.log;
        location /test.html {
                root    /opt/chengke;
                index   index.html;
        }
        location /demo.html {
                alias   /opt/chengke;
                index   index.html;
        }
}
​
# 在 /opt/chengke 目录下创建 test.html 和 demo.html
[root@localhost ~]# echo "test.html" > /opt/chengke/test.html
[root@localhost ~]# echo "demo.html" > /opt/chengke/demo.html
# 验证文件是否创建成功
[root@localhost ~]# ls /opt/chengke/
demo.html  index.html  test.html
​
# 重新启动服务
[root@localhost ~]# systemctl restart nginx
[root@localhost ~]# curl www.chengke.com/test.html
test.html
[root@localhost ~]# curl www.chengke.com/demo.html
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

解决:

        location /demo.html {
                alias   /opt/chengke/demo.html;
                index   index.html;
        }
​
​
[root@localhost ~]# systemctl restart nginx
[root@localhost ~]# curl www.chengke.com/demo.html
demo.html


添加 alias 指令配置:之后修改配置文件,添加了两个新的 location 块。对于 location /test.html,使用 root /opt/chengke;,这和之前的原理一样,访问 www.chengke.com/test.html 时,Nginx 会去 /opt/chengke 目录下找 test.html 文件,所以 curl www.chengke.com/test.html 返回 test.html。而对于 location /demo.html,使用了 alias /opt/chengke;,原本预期访问 www.chengke.com/demo.html 能直接返回 /opt/chengke 目录下的 demo.html 内容,但实际返回了 301 重定向的页面。这是因为 alias 指令的使用方式有误,alias 指令指定的路径应该精确到文件(如果是单个文件的映射)或目录(如果是目录映射),并且目录后面需要加上斜杠 / 来表示这是一个目录。
修正 alias 指令配置:正确的配置应该是 alias /opt/chengke/demo.html;,这样就明确告诉 Nginx,当访问 www.chengke.com/demo.html 时,直接返回 /opt/chengke/demo.html 的内容。修改配置并重启 Nginx 后,执行 curl www.chengke.com/demo.html 成功返回 demo.html。



location里面的参数解释:

/demo.html:这是匹配的请求路径。表示当客户端请求的 URL 路径以 /demo.html 开头时,Nginx 会应用这个 location 块中的配置。
alias /opt/chengke;:alias 指令用于指定一个目录路径,当请求匹配到 location 时,Nginx 会将请求映射到该目录。在这个例子中,它将请求映射到 /opt/chengke 目录。不过需要注意的是,原配置存在问题,根据 Nginx 的规则,如果使用 alias 定义了一个文件或目录,那么在请求该路径时,Nginx 会严格按照 alias 指定的路径来查找,而不会像使用 root 指令那样进行额外的拼接。所以原配置中访问 /demo.html 时出现 301 错误,是因为 Nginx 没有找到正确的文件路径。修改后的 alias /opt/chengke/demo.html; 才是正确的配置,这样 Nginx 就能准确找到 demo.html 文件。
index index.html;:index 指令用于指定当请求的是一个目录时,Nginx 会优先查找并返回的默认文件名。这里指定为 index.html,意味着如果请求的是一个目录,且该目录下存在 index.html 文件,Nginx 会将其作为默认页面返回。

location

精确匹配

在 location 中可以使用 = 来进行精确匹配。

[root@localhost ~]# vim /etc/nginx/conf.d/chengke.conf
server {
        listen  80;
        server_name     www.chengke.com;
        location = /test.html {
                root    /opt/chengke;
                index   index.html;
        }
}
# 重新启动服务
[root@localhost ~]# systemctl restart nginx
# 分别创建三个与 test.html 相似的文件
[root@localhost ~]# echo "Test.html" > /opt/chengke/Test.html
[root@localhost ~]# echo "test1.html" > /opt/chengke/test1.html
[root@localhost ~]# echo "test.htm" > /opt/chengke/test.htm
​
# 测试test.html,它是可以精确匹配的
[root@localhost ~]# curl www.chengke.com/test.html
test.html
# 由于不能精确匹配,所以报 404 错误
[root@localhost ~]# curl www.chengke.com/test.htm
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# curl www.chengke.com/test1.html
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
​
区分大小写

通过在 location 上配置 ~ 来进行区分大小写的匹配。

[root@localhost ~]# vim /etc/nginx/conf.d/chengke.conf
server {
        listen  80;     
        server_name     www.chengke.com;
        location ~ /test.html {
                root    /opt/chengke;
                index   index.html;
        }
}
​
# 重新启动服务
[root@localhost ~]# systemctl restart nginx
# 测试可以匹配上的
[root@localhost ~]# curl www.chengke.com/test.html
test.html
# 由于是区分大小写的,所以 test.html 和 Test.html 是不一要的,所以它不能匹配成功
[root@localhost ~]# curl www.chengke.com/Test.html
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
​
不区分大小写

在 location 中使用 ~* 来匹配不区分大小写匹配。

[root@localhost ~]# vim /etc/nginx/conf.d/chengke.conf
server {
        listen  80;
        server_name     www.chengke.com;
        location ~* /test.html {
                root    /opt/chengke;
                index   index.html;
        }
}
​
# 重新启动服务
[root@localhost ~]# systemctl restart nginx
# 测试小写
[root@localhost ~]# curl www.chengke.com/test.html
test.html
# 测试大写
[root@localhost ~]# curl www.chengke.com/Test.html
Test.html

基于端口配置

首先创建端口配置文件,假设我们监听的是 9000 端口,那么我们创建的配置文件就叫 9000.conf

[root@localhost ~]# vim /etc/nginx/conf.d/9000.conf
server {
        listen  9000;
        server_name     www.chengke.com;
        root    /opt/chengke/9000;
} 
​
# 创建目录
[root@localhost ~]# mkdir /opt/chengke/9000
# 启动服务
[root@localhost ~]# systemctl restart nginx
# 创建文件
[root@localhost ~]# echo "9000 index.html" > /opt/chengke/9000/index.html
​
# 测试
[root@localhost ~]# curl www.chengke.com:9000
9000 index.html

基于IP地址配置

我们在 /etc/nginx/conf.d 目录下新 135.conf 配置文件(这里根据自己的IP命名,不是必要)

[root@localhost ~]# ip a show ens160
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:e1:bb:6b brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 192.168.182.129/24 brd 192.168.182.255 scope global dynamic noprefixroute ens160
       valid_lft 1762sec preferred_lft 1762sec
    inet6 fe80::20c:29ff:fee1:bb6b/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

[root@localhost ~]# ip ad
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:e1:bb:6b brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 192.168.182.129/24 brd 192.168.182.255 scope global dynamic noprefixroute ens160
       valid_lft 1755sec preferred_lft 1755sec
    inet6 fe80::20c:29ff:fee1:bb6b/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
两个命令都能查看
​
# 创建配置文件
[root@localhost ~]# vim /etc/nginx/conf.d/129.conf
server {
        listen  80;
        server_name     192.168.72.129;
        root    /opt/chengke/129;
}
​
# 创建相关目录,用于存放项目文件
[root@localhost ~]# mkdir /opt/chengke/129 -p
# 重新启动服务
[root@localhost ~]# systemctl restart nginx
# 创建基于IP访问的首页
[root@localhost ~]# echo "129 index.html" > /opt/chengke/129/index.html
# 测试基于IP地址的配置
[root@localhost ~]# curl 192.168.182.129
129 index.html

账号验证访问配置

安装加密工具

[root@localhost ~]# dnf install httpd-tools -y
Last metadata expiration check: 1:47:05 ago on Sun 23 Mar 2025 02:40:52 PM CST.
Dependencies resolved.
==========================================================================================================
 Package                      Architecture       Version                      Repository             Size
==========================================================================================================
Installing:
 httpd-tools                  x86_64             2.4.62-1.el9                 appStream              86 k
Installing dependencies:
 apr                          x86_64             1.7.0-12.el9_3               appStream             126 k
 apr-util                     x86_64             1.6.1-23.el9                 appStream              97 k
 apr-util-bdb                 x86_64             1.6.1-23.el9                 appStream              14 k
Installing weak dependencies:
 apr-util-openssl             x86_64             1.6.1-23.el9                 appStream              17 k
​
Transaction Summary
==========================================================================================================
Install  5 Packages
​
Total size: 340 k
Installed size: 737 k
Downloading Packages:
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                  1/1 
  Installing       : apr-1.7.0-12.el9_3.x86_64                                                        1/5 
  Installing       : apr-util-bdb-1.6.1-23.el9.x86_64                                                 2/5 
  Installing       : apr-util-openssl-1.6.1-23.el9.x86_64                                             3/5 
  Installing       : apr-util-1.6.1-23.el9.x86_64                                                     4/5 
  Installing       : httpd-tools-2.4.62-1.el9.x86_64                                                  5/5 
  Running scriptlet: httpd-tools-2.4.62-1.el9.x86_64                                                  5/5 
  Verifying        : apr-1.7.0-12.el9_3.x86_64                                                        1/5 
  Verifying        : apr-util-1.6.1-23.el9.x86_64                                                     2/5 
  Verifying        : apr-util-bdb-1.6.1-23.el9.x86_64                                                 3/5 
  Verifying        : apr-util-openssl-1.6.1-23.el9.x86_64                                             4/5 
  Verifying        : httpd-tools-2.4.62-1.el9.x86_64                                                  5/5 
Installed products updated.
​
Installed:
  apr-1.7.0-12.el9_3.x86_64             apr-util-1.6.1-23.el9.x86_64     apr-util-bdb-1.6.1-23.el9.x86_64 
  apr-util-openssl-1.6.1-23.el9.x86_64  httpd-tools-2.4.62-1.el9.x86_64 
​
Complete!

创建访问账号



# 创建zhangsan用户,它的密码是123456,用户信息保存在 passwdfile 文件中
[root@localhost ~]# htpasswd -cb passwdfile zhangsan 123456
Adding password for user zhangsan

# 创建lisi用户,它的密码是123456,用户信息保存在 passwdfile 文件中
[root@localhost ~]# htpasswd -b passwdfile lisi 123456
Adding password for user lisi

htpasswd是一个用于创建和管理密码文件的工具,通常用于为需要身份验证的网站或服务生成用户名和密码的存储文件,其作用主要体现在以下几个方面:
基本身份验证:在 Web 服务器等环境中,htpasswd用于创建和维护包含用户名和加密密码的文件。当用户访问受保护的资源时,服务器会使用该文件来验证用户提供的用户名和密码是否正确,以此决定是否允许用户访问。
保护网站资源:可以通过.htaccess文件配合htpasswd生成的密码文件,对网站的特定目录或文件进行访问限制。只有提供了正确用户名和密码的用户才能访问这些受保护的内容,从而增加网站资源的安全性。
与多种服务器兼容:htpasswd生成的密码文件格式被许多 Web 服务器和应用程序所支持,如 Apache、Nginx 等。这使得它在不同的服务器环境中都能方便地用于实现用户身份验证功能,具有较好的通用性和可移植性。
​
# 查看密码文件
[root@localhost ~]# cat passwdfile 
zhangsan:$apr1$bVzZtwGq$tzqy/ezWyV1yF2FEsKFvo0
lisi:$apr1$SpgMNXrj$3G4z2KiT2CBlEB3JXHaim0

​
[root@localhost conf.d]# ll passwdfile 
-rw-r--r--. 1 root root 90 Mar 23 17:16 passwdfile
​
# 修改密码文件的权限
[root@localhost conf.d]# chmod 600 passwdfile 
[root@localhost conf.d]# chown nginx passwdfile
​
[root@localhost conf.d]# ll passwdfile 
-rw-------. 1 nginx root 90 Mar 23 17:16 passwdfile

映射IP和域名

# 配置IP和域名的映射
[root@localhost ~]# echo "192.168.72.135   www.account.com" >> /etc/hosts
# 测试配置是否正确
[root@localhost ~]# ping www.account.com
PING www.account.com (192.168.72.135) 56(84) bytes of data.
64 bytes from www.chengke.com (192.168.72.135): icmp_seq=1 ttl=64 time=0.050 ms
64 bytes from www.chengke.com (192.168.72.135): icmp_seq=2 ttl=64 time=0.127 ms
^C
--- www.account.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1019ms
rtt min/avg/max/mdev = 0.050/0.088/0.127/0.038 ms

创建nginx配置文件

server {
        listen  80;
        server_name     www.account.com;
        root    /opt/account;
        location /admin {
                auth_basic      "input you password";
                auth_basic_user_file    /etc/nginx/conf.d/passwdfile;
        }
}

创建目录和文件

# 创建目录
[root@localhost ~]# mkdir /opt/account
# 创建文件
[root@localhost ~]# echo account content > /opt/account/index.html
# 创建目录
[root@localhost ~]# mkdir /opt/account/admin
# 创建文件
[root@localhost ~]# echo account admin content > /opt/account/admin/index.html

功能测试

# 1. 启动服务
[root@localhost conf.d]# systemctl start nginx
# 2. 访问根下面的index.html是可以的。
[root@localhost conf.d]# systemctl start nginx
[root@localhost conf.d]# curl http://www.account.com
account content
​
# 3. 但是访问admin下的index.html则不能访问,需要有权限
[root@localhost conf.d]# curl http://www.account.com/admin/index.html
<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
出现 401 Authorization Required 错误是因为你配置了 auth_basic 基本身份验证,而在使用 curl 访问时没有提供正确的用户名和密码信息,Nginx 拒绝了你的请求。
auth_basic 指令开启了基本身份验证功能,auth_basic_user_file 指令指定了包含用户名和密码信息的文件路径。当客户端发起请求时,Nginx 会检查请求中是否包含有效的身份验证凭据,如果没有或者凭据不正确,就会返回 401 错误。
如果你想使用 curl 进行身份验证并成功访问该资源,可以按照以下方式提供用户名和密码:
假设你在 auth_basic_user_file 指定的文件(比如 /root/password)中设置了用户名 user 和密码 password,你可以使用以下命令:

curl -u user:password http://www.account.com
这里的 -u 选项用于指定用户名和密码,格式为 用户名:密码。这样 curl 就会在请求中带上身份验证信息,Nginx 验证通过后就会返回相应的内容。
另外,确保你的用户名和密码与 auth_basic_user_file 文件中设置的一致,并且该文件的权限设置正确,Nginx 能够读取该文件获取身份验证信息。
​
# 4.在访问时加上用户名和密码就可以成功访问了。
[root@localhost conf.d]# curl http://zhangsan:123456@www.account.com/admin/index.html
account admin content



主播遇到的问题:输入账号后依然会出现500的情况。
tail -n 50 /var/log/nginx/error.log   查询错误日志
2025/03/24 18:37:31 [crit] 38975#38975: *13 open() "/etc/nginx/conf.d/passwdfile" failed (13: Permission denied), client: 192.168.182.129, server: www.account.com, request: "GET /admin/index.html HTTP/1.1", host: "www.account.com"
2025/03/24 18:39:23 [crit] 38975#38975: *14 open() "/etc/nginx/conf.d/passwdfile" failed (13: Permission denied), client: 192.168.182.129, server: www.account.com, request: "GET /admin/index.html HTTP/1.1", host: "www.account.com"
部分
显示没有权限,但是其实跟修改权限没有关系:以下方法可以解决,不过也不一定会遇到这个问题

检查并调整 SELinux 或 AppArmor 配置
若你启用了 SELinux 或者 AppArmor,需要检查它们的配置是否对 Nginx 进程访问 /etc/nginx/conf.d/accounts 文件进行了限制。
SELinux:你可以临时禁用 SELinux 来验证是否是它导致的问题:

setenforce 0

不过,这只是临时解决办法,不建议长期禁用 SELinux。你可以通过修改 SELinux 策略来允许 Nginx 访问该文件:

semanage fcontext -a -t httpd_sys_content_t "/etc/nginx/conf.d/accounts"
restorecon -v "/etc/nginx/conf.d/accounts"

AppArmor:检查 AppArmor 配置文件(通常位于 /etc/apparmor.d/ 目录下),确保 Nginx 的配置文件允许访问 /etc/nginx/conf.d/accounts 文件。

[root@localhost conf.d]# setenforce 0
[root@localhost conf.d]# curl http://zhangsan:123456@www.account.com/admin/index.html
account admin content



http://www.kler.cn/a/599578.html

相关文章:

  • 高级java每日一道面试题-2025年3月09日-微服务篇[Eureka篇]-说一说Eureka自我保护模式
  • AI日报 - 2025年3月25日
  • 2018扬州大学876农业机械学概论填空名词解释简答
  • leetcode1109. 航班预订统计-medium
  • 批量配置Linux ~/.bash_profile
  • 【蓝桥杯每日一题】3.20
  • 阅读li2019-DOT源码--逐步调试
  • 第八课:Python高级排序算法:分治策略的深度应用与实践
  • 生产部署与多框架支持
  • 从零开始实现 C++ TinyWebServer 项目总览
  • 常见框架漏洞—中间件IIS
  • Filnk并行度和算子链
  • Python前缀和(例题:异或和,求和)
  • Java中static final才是修饰常量的,单独的final并不能修饰常量这样理解对吗?
  • Codeforces Round 1012 (Div. 2)
  • JSONP 漏洞
  • Thinkphp(TP)框架漏洞攻略
  • HarmonyOS NEXT (六):系统安全架构
  • 内核中的互斥量
  • 《Python实战进阶》第31集:特征工程:特征选择与降维技术