在Linux系统上使用LNMP(Linux, Nginx, MySQL/MariaDB, PHP)搭建博客是一个相对简单的过程。以下是一个基本的步骤指南:
首先,更新你的包列表并安装Nginx:
sudo apt update
sudo apt install nginx
启动Nginx并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
安装MySQL或MariaDB:
sudo apt update
sudo apt install mysql-server # 安装MySQL
# 或者
sudo apt install mariadb-server # 安装MariaDB
启动MySQL/MariaDB并设置开机自启:
sudo systemctl start mysql
# 或者
sudo systemctl start mariadb
sudo systemctl enable mysql
# 或者
sudo systemctl enable mariadb
运行安全脚本以设置root密码和其他安全选项:
sudo mysql_secure_installation
安装PHP及其常用扩展:
sudo apt update
sudo apt install php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-pear php-bcmath
启动PHP-FPM并设置开机自启:
sudo systemctl start php7.4-fpm # 根据你的PHP版本调整
sudo systemctl enable php7.4-fpm
编辑Nginx配置文件(通常位于/etc/nginx/sites-available/default
):
sudo nano /etc/nginx/sites-available/default
在server
块中添加以下内容:
server {
listen 80;
server_name your_domain.com www.your_domain.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
}
location ~ /\.ht {
deny all;
}
}
保存并退出编辑器,然后测试Nginx配置:
sudo nginx -t
重新加载Nginx以应用更改:
sudo systemctl reload nginx
登录到MySQL/MariaDB并创建一个新的数据库和用户:
sudo mysql -u root -p
在MySQL shell中执行以下命令:
CREATE DATABASE blog_db;
CREATE USER 'blog_user'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON blog_db.* TO 'blog_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
你可以选择安装WordPress、Ghost、Hexo等博客系统。这里以WordPress为例: 下载WordPress:
cd /var/www/html
sudo wget https://wordpress.org/latest.tar.gz
sudo tar -xzvf latest.tar.gz
sudo mv wordpress/* .
sudo rm -rf wordpress latest.tar.gz
创建一个MySQL数据库和用户用于WordPress:
CREATE DATABASE wordpress_db;
CREATE USER 'wordpress_user'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON wordpress_db.* TO 'wordpress_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
编辑WordPress的wp-config.php
文件以配置数据库连接:
sudo nano /var/www/html/wp-config.php
修改以下行:
define('DB_NAME', 'wordpress_db');
define('DB_USER', 'wordpress_user');
define('DB_PASSWORD', 'your_password');
define('DB_HOST', 'localhost');
打开浏览器并访问你的域名(例如http://your_domain.com
),按照WordPress的安装向导完成安装。
确保你的防火墙允许HTTP和HTTPS流量:
sudo ufw allow 'Nginx Full'
现在,你的博客应该已经成功搭建并可以访问了。你可以根据需要进一步自定义和优化你的博客系统。