温馨提示×

ubuntu apache2如何设密码

小樊
63
2026-09-11 03:03:37
栏目: 智能运维

在 Ubuntu 上用 Apache2 给网站或目录设置访问密码,通常有两种常见做法:


方法一:使用 Apache 自带认证(htpasswd,最常用)

1️⃣ 安装必要工具

sudo apt update
sudo apt install apache2 apache2-utils

2️⃣ 创建密码文件

sudo htpasswd -c /etc/apache2/.htpasswd 用户名

示例:

sudo htpasswd -c /etc/apache2/.htpasswd admin

第一次用 -c,之后再加用户 不要加 -c,否则会覆盖。

查看文件:

cat /etc/apache2/.htpasswd

3️⃣ 配置 Apache 保护目录

方式 A:修改站点配置(推荐)

编辑站点配置:

sudo nano /etc/apache2/sites-available/000-default.conf

在 <VirtualHost> 里加:

<Directory /var/www/html/secret>
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
</Directory>

保存后:

sudo systemctl restart apache2

方式 B:使用 .htaccess(适合快速测试)

  1. 允许 .htaccess
sudo nano /etc/apache2/apache2.conf

找到:

<Directory /var/www/>
    AllowOverride None

改成:

AllowOverride All
  1. 在要保护的目录创建 .htaccess
sudo nano /var/www/html/secret/.htaccess

内容:

AuthType Basic
AuthName "Restricted"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
  1. 重启 Apache
sudo systemctl restart apache2

方法二:仅限制 IP(无密码)

如果你只是想限制访问来源:

<Directory /var/www/html/secret>
    Require ip 192.168.1.100
</Directory>

常见排查

  • 403 Forbidden → 目录权限或 AllowOverride 没开
  • 密码无效 → htpasswd 路径写错
  • 不弹窗 → 浏览器缓存,或目录未正确匹配

如果你愿意,可以告诉我:

  • 是 整个网站 还是 某个目录
  • 用的是 Apache 默认站点 还是 Docker / 宝塔 / LNMP

我可以直接给你一份完整配置。

0 踩