搭建个人博客并没有想象中那么复杂。从一台空白的服务器,到能用 https 访问的网站,全程也就几大步。这篇文章把我踩过的坑和完整流程记录下来。
一、准备
服务器用的是阿里云轻量应用服务器,系统 Ubuntu 22.04。技术栈就是经典的 LNMP:Linux + Nginx + MySQL + PHP。
整体分工一句话就能讲清:
- Nginx:接待请求,把 .php 交给 fpm,静态文件自己处理
- MySQL:存数据
- PHP-FPM:解析执行 PHP 代码
二、部署 LNMP
1. 环境准备,先更新系统并设置时区:
apt update && apt upgrade -y
timedatectl set-timezone Asia/Shanghai
2. 安装 Nginx:
apt install nginx -y
systemctl enable --now nginx
curl -I http://127.0.0.1 # 验证
3. 安装 MySQL,并做安全初始化:
apt install mysql-server -y
systemctl enable --now mysql
mysqlsecureinstallation # 安全初始化
然后建库建用户,给网站专用(不要用 root):
CREATE DATABASE wpdb DEFAULT CHARACTER SET utf8mb4;
CREATE USER ‘wpuser’@‘localhost’ IDENTIFIED BY ‘你的强密码’;
GRANT ALL ON wpdb.* TO ‘wpuser’@‘localhost’;
FLUSH PRIVILEGES;
4. 安装 PHP 和 PHP-FPM(含常用扩展):
apt install php php-fpm php-mysql php-common php-cli
php-gd php-mbstring php-xml php-curl php-zip -y
systemctl enable --now php8.1-fpm
ls /run/php/ # 看 sock 名,后面配置要用
5. 配置 Nginx 关联 PHP(最关键的一步)。编辑 /etc/nginx/sites-enabled/default:
server {
listen 80 defaultserver;
listen [::]:80 defaultserver;
root /var/www/html;
index index.html index.htm index.php;
servername ;
location / {
try_files uriuri/ =404;
}
location ~ .php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.1-fpm.sock; # 按实际 php 版本
}
}
改完一定要验证:
nginx -t && systemctl reload nginx
三、安装 WordPress
下载并解压 WordPress 到 /var/www/html:
cd /var/www/html
wget https://wordpress.org/latest.tar.gz
tar xzf latest.tar.gz
mv wordpress/* . ; rm -rf wordpress latest.tar.gz
chown -R www-data:www-data /var/www/html
chmod -R 755 /var/www/html && chmod -R 775 /var/www/html/wp-content
浏览器访问 http://你的IP,填入数据库信息(wpdb / wpuser / 密码 / localhost),再设置站点标题和管理员账号即可完成。
四、开启 HTTPS
有域名后,用 certbot 申请 Let’s Encrypt 证书:
apt install certbot python3-certbot-nginx -y
certbot --nginx -d www.你的域名 -d 你的域名
五、遇到的问题
问题 1:PHP 解析失败 / 访问 .php 触发下载
原因是 Nginx 没把 .php 请求转给 PHP-FPM,而是当静态文件返回了。检查 location ~ \.php$ 是否在 server 块内、fastcgi_pass 的 sock 路径是否和 /run/php/ 里的实际版本一致。
问题 2:443 端口 / HTTPS 打不开
确认安全组和防火墙都放行了 443:
ufw allow 80,443/tcp
ss -tlnp | grep -E ‘:80|:443’
问题 3:混合内容(Mixed Content)
开启 HTTPS 后,页面里若还有 http:// 的资源会被浏览器拦截。把所有站内资源统一改成 https:// 。
总结
搭建网站并不复杂,关键是有耐心,一步一步排查每一个细节。遇到报错别慌,看日志、验证配置,问题总能解决。