准备工作
-
选择Linux发行版
推荐Ubuntu Server LTS(长期支持版)或CentOS Stream,两者拥有完善的文档和社区支持,本文以Ubuntu 22.04 LTS为例。 -
服务器基础配置
- 通过SSH连接服务器:
ssh username@server_ip
- 更新系统:
sudo apt update && sudo apt upgrade -y
- 创建非root用户(提升安全性):
sudo adduser deploy sudo usermod -aG sudo deploy
- 通过SSH连接服务器:
核心组件安装
LAMP 栈(Apache)
sudo systemctl enable --now apache2 # 安装MySQL sudo apt install mysql-server -y sudo mysql_secure_installation # 按提示设置root密码 # 安装PHP sudo apt install php libapache2-mod-php php-mysql -y sudo systemctl restart apache2
LEMP 栈(Nginx)
# 安装Nginx sudo apt install nginx -y sudo systemctl enable --now nginx # 安装MySQL(同上) sudo apt install mysql-server -y # 安装PHP-FPM sudo apt install php-fpm php-mysql -y sudo systemctl enable --now php8.1-fpm # 版本号需匹配
关键配置步骤
防火墙设置
sudo ufw allow OpenSSH sudo ufw allow http sudo ufw allow https sudo ufw enable
虚拟主机配置(以Nginx为例)
sudo nano /etc/nginx/sites-available/yourdomain.com
server { listen 80; server_name yourdomain.com www.yourdomain.com; root /var/www/yourdomain.com/html; index index.php index.html; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.1-fpm.sock; } }
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/ sudo nginx -t # 测试配置 sudo systemctl reload nginx
文件权限管理
sudo chown -R www-data:www-data /var/www/yourdomain.com/html sudo chmod -R 755 /var/www
安全加固措施
-
SSH安全
- 修改默认端口:
sudo nano /etc/ssh/sshd_config
→ 修改Port
- 禁用root登录:
PermitRootLogin no
- 重启服务:
sudo systemctl restart sshd
- 修改默认端口:
-
安装Fail2Ban
sudo apt install fail2ban -y sudo systemctl enable fail2ban
-
配置SSL证书(Let’s Encrypt)
sudo apt install certbot python3-certbot-nginx -y sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com # 自动续期验证 sudo certbot renew --dry-run
验证与测试
- 创建测试页面:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/yourdomain.com/html/info.php
- 访问测试:
- HTTP:
http://server_ip
- PHP:
http://yourdomain.com/info.php
- HTTPS:
https://yourdomain.com
(证书生效后)
- HTTP:
后期维护建议
- 定期更新
sudo apt update && sudo apt upgrade -y sudo apt autoremove
- 日志监控
- Apache日志:
/var/log/apache2/access.log
- Nginx日志:
/var/log/nginx/access.log
- Apache日志:
- 备份策略
- 数据库备份:
mysqldump -u user -p database > backup.sql
- 网站文件备份:
tar -czvf website_backup.tar.gz /var/www/
- 数据库备份:
故障排查命令
# 检查服务状态 systemctl status apache2/nginx/mysql # 查看错误日志 tail -f /var/log/nginx/error.log journalctl -xe -u nginx --since "5 minutes ago" # 测试端口连通性 sudo lsof -i :80 curl -I http://localhost
引用说明
本文操作基于Ubuntu官方文档(https://ubuntu.com/server/docs)及Nginx/Apache社区最佳实践,安全配置参考Linux基金会安全指南(https://training.linuxfoundation.org),Let’s Encrypt证书部署遵循EFF官方教程(https://certbot.eff.org)。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/9746.html