Ubuntu安装配置Apache及SSL简单配置

张开发
2026/4/11 12:04:52 15 分钟阅读

分享文章

Ubuntu安装配置Apache及SSL简单配置
一、安装Apachesudo apt update (更新同步信息)sudo apt install apache2 -y (安装Apache没有-y会交互式安装)apache2 -version (验证是否安装)安装完成后Apache服务会自动启动sudo systemctl status apache2 (检查运行状态activerunning成功启动)二、配置防火墙sudo ufw app list (列出UFW防火墙中所有已定义的应用程序配置文件)1. Apache 只放行 80端口HTTP​2. Apache Secure 只放行 443端口HTTPS/SSL​3. Apache Full 同时放行 80 443httphttps全部通过sudo ufw allow Apache Full (放行80443两个端口http和https都通过)sudo ufw status (查看防火墙状态)三、验证安装hostname- I (显示本机当前配置的所有IP地址)打开浏览器http://IP地址 逐个尝试看到Apache默认欢迎页面即成功四、设置虚拟主机创建自己的第一个网站sudo mkdir -p /var/www/自己取名.com/html 存放网页文件sudo chown -R $USER:$USER /var/www/自己取名.com/htmlsudo chmod -R 755 /var/www/自己取名.com 分配目录所有权sudo nano /var/www/自己取名.com/html/index.html 使用文本编辑器:nano/gedit/code[vscode]等创建HTML文件sudo nano /etc/apache2/sites-available/自己取名.com.conf 为自定义配置创建一个新配置文件VirtualHost *:80ServerAdmin admin自己取名.comServerName 自己取名.comServerAlias www.自己取名.comDocumentRoot /var/www/自己取名.com/htmlErrorLog ${APACHE_LOG_DIR}/error.logCustomLog ${APACHE_LOG_DIR}/access.log combined/VirtualHost在文件中粘贴sudo a2ensite example.com.conf 启用配置文件sudo a2dissite 000-default.conf 禁止了默认站点sudo systemctl restart apache2 重启Apache服务sudo apache2ctl configtest 测试是否存在配置错误五、可通过修改Hosts文件建立域名和IP地址的映射关系修改文件后可用域名访问hostname- I 查看IP地址sudo nano /etc/hosts在文件末尾添加IP地址 自己取名.com(修改文件建立映射)随后即可在浏览器用http://自己取名.com访问六、自签名SSL配置一生成自签名证书1. 创建私钥文件server.keyopenssl genrsa -des3 -out server.key 2048生成2048位RSA私钥 -des3 给私钥加密码保护若去掉 -des3 则无需密码2. 创建CSR证书签名请求server.csropenssl req -new -key server.key -out server.csr用私钥生成证书签名请求用于后续签发证书执行后需填写信息参考如下可按需修改Country Name 国家代码中国填CNState or Province Name 省份全称大写Locality Name 城市名Organization Name 公司/组织名Organizational Unit Name 部门/单位名Common Name virtual-machine 关键填写你的主机名/域名必须和访问地址一致否则浏览器会报错Email Address 联系邮箱Challenge password 留空回车 挑战密码无需填写Optional company name 留空回车 可选公司名无需填写3. 自签发证书server.crtopenssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt用私钥对CSR进行自签名生成有效期10年3650天的SSL证书执行成功后当前目录会生成3个核心文件server.key 私钥必须严格保密不可泄露server.csr 证书请求文件可删除server.crt 自签名证书公钥4. 证书文件部署sudo cp server.crt /etc/ssl/certs/sudo cp server.key /etc/ssl/private/将证书和私钥复制到Apache2默认证书目录方便后续配置引用二修改SSL配置文件default-ssl.conf1. 启用SSL模块sudo a2enmod ssl启用Apache2的SSL模块否则配置不生效2.复制ssl配置到生效目录sudo cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-enabled/default-ssl.conf把原本在可用目录的ssl配置文件复制一份到启用目录让apache能读取这个配置生效Apache 结构常识/etc/apache2/sites-available 存放所有配置文件可用站点​ /etc/apache2/sites-enabled 存放启用生效的配置3.打开生效目录里的ssl文件核心配置修改sudogedit /etc/apache2/sites-enabled/default-ssl.conf三重启服务并验证1. 检查配置语法sudo apache2ctl configtest若输出Syntax OK说明配置正确若报错根据提示修正配置2. 重启Apache2服务sudo systemctl restart apache23. 访问验证浏览器访问 https://域名注意自签名证书浏览器会提示“不安全”属于正常现象手动信任证书即可访问

更多文章