开启 apcache http server 可以通过公网访问服务器 /var/www/html目录下的文件/目录。
但是每次把文件复制过去比较麻烦。经常改动的 html 文件,又想马上看到网页效果,则可以使用软连接,把工作的文件目录链接到 /var/www/html目录。
以下是踩坑记录。

/var/www/html 目录建立软连接

  1. 使用 ln -s 文件或目录 /var/www/html
  2. 然后公网访问 ip地址/文件或目录

~/public_html 目录建立软连接

如果想根据用户分别公开,则继续往下看。

  1. 开启 userdir 模块功能

    1. sudo a2enmod userdir

    a2enmod userdir 做的事情其实就是把 /etc/apache2/mods-available 的两个模块配置文件软连接到 /etc/apache2/mods-enabled 下:

    1. # 无需再链接了
    2. /etc/apache2/mods-enabled/userdir.conf -> ../mods-available/userdir.conf
    3. /etc/apache2/mods-enabled/userdir.load -> ../mods-available/userdir.load
  2. 修改 /etc/apache2/mods-available/userdir.conf 文件内容:

    1. <IfModule mod_userdir.c>
    2. UserDir public_html
    3. UserDir disabled
    4. UserDir enabled ubuntu
    5. <Directory /home/*/public_html>
    6. AllowOverride FileInfo AuthConfig Limit Indexes
    7. Options MultiViews Indexes FollowSymLinks IncludesNoExec
    8. Require method GET POST OPTIONS
    9. </Directory>
    10. </IfModule>

    重点配置 UserDir enabled 用户名Options FollowSymLinks 两项内容。
    UserDir public_html/home/*/public_html 表明 UserDir enabled 的用户主目录下使用 public_html 目录来公开访问,而且访问的方式为:ip地址/~用户名/public_html下的具体内容
    详细描述参考:https://httpd.apache.org/docs/2.4/en/mod/mod_userdir.html

  3. 重启 apache2 服务

    1. sudo systemctl restart apache2 # 重启 apache2
  4. 建立软连接到 ~/public_htmlln -s 文件或目录 ~/public_html

  5. 公网访问 ip地址/~用户名/public_html下的具体内容

比如我作为 ubuntu 用户,把 book/ 目录软连接到 ~/public_html 下(即 /home/ubuntu/public_html/book/ 存在),那么输入网址 http:x.x.x.x/~ubuntu/book 即可。

解决 403 Forbidden

无论是方法一还是方法二,如果打开网址显示:You don’t have permission to access this resource. 说明软连接失败。
查看 apache 报错日志:tail -20 /var/log/apache2/error.log,会发现一句

  1. Symbolic link not allowed or link target not accessible: /../book

所以你需要两方面排查问题。

  • Symbolic link not allowed:说明你需要确认 /etc/apache2/apache2.conf/etc/apache2/mods-available/userdir.conf 等文件里面有没有开启 Options FollowSymLinks;如果是链接不同的用户创建的文件,还不能有 Options SymLinksIfOwnerMatch 这项配置。
  • link target not accessible:说明你的软连接有问题。

    • 首先,软连接需要 x 权限,检查来源路径是不是都支持 x,试图用 sudo chmod g+x 文件/目录 解决(给所在用户组所有成员添加该文件/目录的执行权限)。注意,不仅仅是检查源文件,还得检查其上级、上上级一直到+包括 /home/用户名 都需要 x 权限。
    • 如果还是不能解决问题,考虑建立用户组。使用 sudo usermod -g 用户组名 用户名 将用户放在一个组管理,然后使用 chmod 修改权限,见上一条。

    一些命令帮助你解决权限方面的问题:

  1. stat 文件/目录 可以查看其权限信息
  2. chown -R 用户名:用户组 目录 可以变更目录所有者/用户组