服务器环境安装教程
准备工作
选择操作系统
推荐使用Linux发行版(如Ubuntu 22.04 LTS或CentOS 7/8),因其稳定性与开源生态支持广泛。
硬件要求
网络与安全
ufw
或firewalld
),仅允许必要端口。 基础环境安装
步骤1:更新系统
# Ubuntu/Debian sudo apt update && sudo apt upgrade -y # CentOS/RHEL sudo yum update -y
步骤2:安装必要工具
# Ubuntu/Debian sudo apt install -y curl wget git unzip # CentOS/RHEL sudo yum install -y curl wget git unzip
安装Web服务器
方案1:Nginx(推荐)
# Ubuntu/Debian sudo apt install -y nginx sudo systemctl start nginx sudo systemctl enable nginx # CentOS/RHEL sudo yum install -y epel-release sudo yum install -y nginx sudo systemctl start nginx sudo systemctl enable nginx
方案2:Apache
# Ubuntu/Debian sudo apt install -y apache2 sudo systemctl start apache2 sudo systemctl enable apache2 # CentOS/RHEL sudo yum install -y httpd sudo systemctl start httpd sudo systemctl enable httpd
安装数据库
MySQL/MariaDB
# Ubuntu/Debian sudo apt install -y mariadb-server sudo mysql_secure_installation # 按提示设置密码与安全选项 # CentOS/RHEL sudo yum install -y mariadb-server sudo systemctl start mariadb sudo systemctl enable mariadb sudo mysql_secure_installation
PostgreSQL
# Ubuntu/Debian sudo apt install -y postgresql postgresql-contrib # CentOS/RHEL sudo yum install -y postgresql-server sudo postgresql-setup --initdb sudo systemctl start postgresql sudo systemctl enable postgresql
安装PHP(适用于动态网站)
安装PHP与扩展
# Ubuntu/Debian sudo apt install -y php-fpm php-mysql php-curl php-gd php-mbstring # CentOS/RHEL sudo yum install -y php php-fpm php-mysqlnd php-curl php-gd
配置PHP与Web服务器
/etc/nginx/sites-available/default
,添加: location ~ .php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php-fpm.sock; }
安装SSL证书(HTTPS)
使用Let’s Encrypt免费证书:
安装Certbot工具
# Ubuntu/Debian sudo apt install -y certbot python3-certbot-nginx # CentOS/RHEL sudo yum install -y certbot python3-certbot-nginx
生成证书
sudo certbot --nginx # 按提示选择域名并配置自动续签
环境验证
Web服务器
访问http://服务器IP
,若看到欢迎页则安装成功。
数据库
mysql -u root -p # 输入密码后进入MySQL命令行
PHP测试
创建/var/www/html/info.php
,写入:
<?php phpinfo(); ?>
访问http://服务器IP/info.php
查看PHP配置信息。
安全加固建议
禁用root远程登录
编辑/etc/ssh/sshd_config
,设置:
PermitRootLogin no
重启SSH服务:systemctl restart sshd
配置自动更新
# Ubuntu/Debian sudo apt install -y unattended-upgrades # CentOS/RHEL sudo yum install -y yum-cron
启用防火墙
# Ubuntu/Debian sudo ufw enable sudo ufw allow 22,80,443 # CentOS/RHEL sudo firewall-cmd --permanent --add-service={ssh,http,https} sudo firewall-cmd --reload
常见问题(FAQ)
无法访问网站?
journalctl -u nginx
或 /var/log/apache2/error.log
数据库连接失败?
GRANT ALL PRIVILEGES ON *.* TO '用户'@'localhost';
/etc/mysql/mariadb.conf.d/50-server.cnf
PHP文件不解析?
systemctl restart php-fpm
参考资料