简介:本文详细介绍如何使用云服务器搭建Hexo个人博客,涵盖服务器选择、环境配置、Hexo部署及安全优化等核心环节,帮助开发者高效完成云端博客搭建。
Hexo作为静态网站生成器,传统部署方式多依赖GitHub Pages或Vercel等免费平台。但云服务器部署具有显著优势:
以某技术博主案例为例,其Hexo博客从GitHub Pages迁移至云服务器后,页面加载时间从2.3秒缩短至0.8秒,同时支持了评论系统和邮件订阅功能。
开放必要端口:
# 更新系统包sudo apt update && sudo apt upgrade -y# 安装Node.js(推荐LTS版本)curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -sudo apt install -y nodejs# 验证安装node -v && npm -v
sudo apt install -y nginx git# 启动Nginx并设置开机自启sudo systemctl start nginxsudo systemctl enable nginx
# 本地生成密钥对(若未生成)ssh-keygen -t ed25519 -C "your_email@example.com"# 将公钥上传至服务器ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server_ip
在服务器/etc/ssh/sshd_config中禁用密码登录:
PasswordAuthentication noChallengeResponseAuthentication no
重启SSH服务:sudo systemctl restart sshd
# 在本地创建项目目录mkdir hexo-blog && cd hexo-bloghexo initnpm install# 生成静态文件hexo generate
# 在服务器创建博客目录sudo mkdir -p /var/www/hexosudo chown -R $USER:$USER /var/www/hexo# 安装PM2进程管理sudo npm install -g pm2pm2 startup # 按提示执行后续命令
创建deploy.sh:
#!/bin/bashhexo cleanhexo generatersync -avz --delete public/ username@server_ip:/var/www/hexo/ssh username@server_ip "pm2 restart hexo"
通过Git Hook或CI/CD工具(如GitHub Actions)实现提交后自动部署。
编辑/etc/nginx/sites-available/hexo:
server {listen 80;server_name yourdomain.com;root /var/www/hexo;index index.html;location / {try_files $uri $uri/ /index.html;}}
启用配置:
sudo ln -s /etc/nginx/sites-available/hexo /etc/nginx/sites-enabled/sudo nginx -t # 测试配置sudo systemctl restart nginx
sudo apt install -y certbot python3-certbot-nginxsudo certbot --nginx -d yourdomain.com
自动续期测试:
sudo certbot renew --dry-run
/etc/nginx/nginx.conf中添加:
gzip on;gzip_types text/plain text/css application/json application/javascript text/xml;
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {expires 1y;add_header Cache-Control "public";}
sudo ufw allow 22/tcpsudo ufw allow 80/tcpsudo ufw allow 443/tcpsudo ufw enable
# 每日备份至云存储0 3 * * * tar -czf /backup/hexo_$(date +\%Y\%m\%d).tar.gz /var/www/hexo && \aws s3 cp /backup/hexo_$(date +\%Y\%m\%d).tar.gz s3://your-bucket/
pm2 monitor
htop、nmon等工具 sudo chown -R www-data:www-data /var/www/hexo) url和root参数正确 ecosystem.config.js中的脚本路径 hexo-generator-feed插件生成RSS源 hexo-generator-seo-helper插件自动生成meta标签 通过云服务器部署Hexo博客,开发者不仅能获得更高的自由度,还能为后续功能扩展(如会员系统、付费内容)打下基础。建议从基础配置入手,逐步优化性能与安全性,最终打造一个稳定、高效的技术博客平台。