温馨提示×

centos lamp怎样部署网站

小樊
40
2026-09-24 11:40:22
栏目: 云计算

下面以 CentOS 7/8(含 Stream) 为例,说明如何搭建 LAMP(Linux + Apache + MySQL/MariaDB + PHP) 并部署一个网站。


一、系统准备

# 更新系统
yum update -y

# 关闭防火墙(测试环境,生产不建议)
systemctl stop firewalld
systemctl disable firewalld

# 或开放端口(推荐)
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

二、安装 LAMP 环境

1. 安装 Apache

yum install httpd -y
systemctl start httpd
systemctl enable httpd

测试:浏览器访问 http://服务器IP


2. 安装 MariaDB(MySQL 替代品)

yum install mariadb-server -y
systemctl start mariadb
systemctl enable mariadb

# 初始化
mysql_secure_installation

创建数据库示例:

mysql -u root -p
CREATE DATABASE testdb;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL ON testdb.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

3. 安装 PHP

yum install php php-mysqlnd php-fpm -y
systemctl restart httpd

测试 PHP:

echo "<?php phpinfo(); ?>" > /var/www/html/info.php

访问 http://IP/info.php


三、部署网站

方式一:直接放到默认目录

# 网站文件放到
/var/www/html/

访问:

http://服务器IP/

方式二:配置虚拟主机(推荐)

  1. 创建网站目录
mkdir -p /var/www/example.com/public_html
  1. 创建配置文件
vi /etc/httpd/conf.d/example.conf

内容:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example.com/public_html
    <Directory /var/www/example.com/public_html>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
  1. 重启 Apache
systemctl restart httpd
  1. 上传网站代码
# 可用 scp / ftp / git
scp -r ./web/* root@IP:/var/www/example.com/public_html

四、常见网站类型部署

1. 静态网站

直接放 HTML 文件即可

2. PHP 网站(如 WordPress)

# 下载
cd /var/www/example.com/public_html
wget https://wordpress.org/latest.tar.gz
tar -xzf latest.tar.gz

配置数据库后访问安装向导

3. 开启伪静态(URL Rewrite)

确保:

AllowOverride All

并启用:

httpd -M | grep rewrite

五、权限设置(重要)

chown -R apache:apache /var/www/example.com
chmod -R 755 /var/www/example.com

六、常见问题

✅ 403 错误

  • SELinux 未关闭或权限不对
setenforce 0
# 或修改
chcon -R -t httpd_sys_content_t /var/www

✅ 无法连接数据库

  • 检查用户权限、localhost 与 127.0.0.1

如果你告诉我:

  • CentOS 具体版本
  • 网站类型(WordPress / 自建 PHP / 静态)
  • 是否用域名

我可以给你 更精确的部署步骤 或 一键脚本。

0 踩