大学网 > php中文网 > 每日编程Apache 虚拟主机:增加安全性正文

Apache 虚拟主机:增加安全性

中国大学网 2024-10-17

为了在使用 Apache 设置反向代理时确保安全性,您可以实施多种最佳实践,例如使用 ssl/tls 启用 https、调整安全标头,配置防火墙,以及保护对后端的访问。下面是一个详细的实现,以确保您有一个更安全的环境。

启用带有 ssl/tls 的 https

使用 https 对于保护客户端和服务器之间的数据至关重要。为此,我们将在 apache 中配置 ssl 证书。

1.安装 certbot 和 apache ssl 模块

如果您尚未安装 ssl 模块,请安装它们:

sudo apt install certbot python3-certbot-apache
sudo a2enmod ssl

2.获取 ssl 证书(let's encrypt)

如果您的域名已经指向服务器,您可以从 let's encrypt with certbot 获取免费的 ssl 证书。运行以下命令:

sudo certbot --apache -d php.info
  • 如果域名是公共域名,请将 php.info 替换为您的实际域名。

  • certbot 将自动在您的虚拟主机上配置 ssl 并将 http 流量重定向到 https。

3.验证并调整虚拟主机 ssl

配置后,certbot 将创建或修改虚拟主机 ssl 配置文件。检查一切是否正确:

sudo your_editor /etc/apache2/sites-available/php-le-ssl.conf

它应该看起来像这样:


        serveradmin webmaster@localhost
        servername php.info
        documentroot /var/www/html/php

        # reverse proxy configuration for https
        proxypreservehost on
        proxypass / http://localhost:8080/
        proxypassreverse / http://localhost:8080/

        
            allowoverride all
            require all granted
        

        errorlog ${apache_log_dir}/php_error.log
        customlog ${apache_log_dir}/php_access.log combined

        sslengine on
        sslcertificatefile /etc/letsencrypt/live/php.info/fullchain.pem
        sslcertificatekeyfile /etc/letsencrypt/live/php.info/privkey.pem
        include /etc/letsencrypt/options-ssl-apache.conf
    

将 http 重定向到 https

您可以确保所有 http 流量都重定向到 https。在您的 http 虚拟主机 (/etc/apache2/sites-available/php.conf) 中,添加:


    serveradmin webmaster@localhost
    servername php.info
    redirect permanent / https://php.info/

这将确保任何 http 请求都将重定向到网站的安全 (https) 版本。

安全标头

将以下安全标头添加到您的 ssl 虚拟主机配置文件中,以缓解一些常见漏洞,例如 点击劫持跨站脚本 (xss):


    header always set x-content-type-options "nosniff"
    header always set x-frame-options "sameorigin"
    header always set x-xss-protection "1; mode=block"
    header always set strict-transport-security "max-age=31536000; includesubdomains"
    header always set content-security-policy "default-src 'self';"
  • x-content-type-options:防止浏览器尝试猜测内容类型,减轻 mime 嗅探攻击。
  • x-frame-options:防止在 iframe 中使用网站,防止点击劫持
  • x-xss-protection:启用浏览器中针对 xss 攻击的保护。
  • 严格传输安全:强制浏览器始终使用 https。
  • content-security-policy:定义内容加载策略以防止xss.
  • 等攻击

保护后端

您必须确保后端服务(例如 php 服务器或其他服务)不能被公众直接访问。这可以通过将对后端的访问限制为仅代理来完成。

配置防火墙(ubuntu 上的 ufw):

首先,仅允许 http(端口 80)和 https(端口 443)流量到达服务器。

sudo ufw allow 'apache full'
sudo ufw enable

现在,阻止任何到端口 8080(后端)的直接流量,apache 除外:

sudo ufw deny 8080

监控和日志

密切关注访问和错误日​​志以监控可疑行为:

  • 访问错误日志
tail -f /var/log/apache2/php_error.log
  • 访问访问日志
tail -f /var/log/apache2/php_access.log

您还可以使用监控工具,例如fail2ban,自动阻止多次登录失败或其他可疑活动的 ip 地址。

定期更新

使您的操作系统、apache 和 certbot 保持最新状态对于确保您免受已知漏洞的影响至关重要。

sudo apt update && sudo apt upgrade

通过执行这些步骤,您将拥有一个安全的反向代理环境,具有https和针对常见攻击的基本保护。这些设置涵盖传输安全 (ssl/tls)、减轻通过 http 标头的攻击以及保护后端免受外部访问。

以上就是Apache 虚拟主机:增加安全性的详细内容,更多请关注中国大学网其它相关文章!