Linux LAMP怎样配置虚拟主机
导读:Linux LAMP 虚拟主机配置步骤 一、准备与安装 安装组件(以 CentOS 7/8 为例): 安装:sudo yum install -y httpd mariadb-server php php-mysqlnd 启动并设置开机...
Linux LAMP 虚拟主机配置步骤
一、准备与安装
- 安装组件(以 CentOS 7/8 为例):
- 安装:sudo yum install -y httpd mariadb-server php php-mysqlnd
- 启动并设置开机自启:
- sudo systemctl start httpd & & sudo systemctl enable httpd
- sudo systemctl start mariadb & & sudo systemctl enable mariadb
- 基础安全(可选):运行 sudo mysql_secure_installation 完成 MySQL 安全初始化(设置 root 密码、移除匿名用户等)。
二、创建站点目录与权限
- 创建目录(示例域名:example.com):
- sudo mkdir -p /var/www/example.com/public_html
- 创建测试页:
- echo “” | sudo tee /var/www/example.com/public_html/index.php
- 设置权限(Apache 运行用户通常为 apache):
- sudo chown -R apache:apache /var/www/example.com
- sudo chmod -R 755 /var/www/example.com
三、创建虚拟主机配置
- 新建配置文件:
- sudo vi /etc/httpd/conf.d/example.com.conf
- 写入以下内容(按需修改域名与目录):
< VirtualHost *:80> ServerAdmin webmaster@example.com ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public_html ErrorLog /var/log/httpd/example.com-error.log CustomLog /var/log/httpd/example.com-access.log combined < Directory /var/www/example.com/public_html> Options Indexes FollowSymLinks AllowOverride All Require all granted < /Directory> < /VirtualHost> - 语法检查与生效:
- 检查:sudo httpd -t
- 重载:sudo systemctl reload httpd
- 说明:
- 在 CentOS/RHEL 上,Apache 会自动包含 /etc/httpd/conf.d/*.conf,无需额外启用步骤。
- 若使用 Debian/Ubuntu,需将配置放入 /etc/apache2/sites-available/,执行 sudo a2ensite example.com.conf 启用,必要时 sudo a2dissite 000-default.conf 禁用默认站点,再 sudo systemctl reload apache2。
四、域名解析与本地测试
- 公网域名:在域名注册商控制台将 example.com 与 www.example.com 的 A 记录指向服务器 公网 IP。
- 本机测试(Windows):编辑 C:\Windows\System32\drivers\etc\hosts
- 添加:服务器IP example.com www.example.com
- 浏览器访问:http://example.com 应显示 phpinfo 页面。
- 服务器本机测试(可选):在 /etc/hosts 添加同样记录后使用 curl -I http://example.com 验证。
五、防火墙与 SELinux 及常见问题
- 防火墙(CentOS):
- 开放 HTTP/HTTPS:sudo firewall-cmd --permanent --zone=public --add-service=http & & sudo firewall-cmd --permanent --zone=public --add-service=https & & sudo firewall-cmd --reload
- SELinux(如启用 enforcing):
- 目录上下文(示例):sudo semanage fcontext -a -t httpd_sys_content_t “/var/www/example.com(/.*)?” & & sudo restorecon -R /var/www/example.com
- 若 PHP 需连接数据库,允许网络访问:sudo setsebool -P httpd_can_network_connect_db 1
- 常见问题排查:
- 配置语法:sudo httpd -t
- 服务状态与日志:sudo systemctl status httpd;查看 /var/log/httpd/error_log
- 端口监听:ss -tlnp | grep :80
- 目录权限与 SELinux 上下文是否正确,必要时使用 restorecon 修复。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Linux LAMP怎样配置虚拟主机
本文地址: https://pptw.com/jishu/788604.html
