在Linux虚拟机上搭建Web服务器,可选择Apache或Nginx,以下是基于Ubuntu和CentOS的通用步骤:
在虚拟机中安装Ubuntu或CentOS等Linux发行版,安装过程中可设置网络、用户权限等。
sudo apt update和sudo apt install apache2;CentOS/RHEL系统使用sudo yum install httpd(CentOS 7)或sudo dnf install httpd(CentOS 8+)。sudo apt update和sudo apt install nginx安装;CentOS/RHEL系统需先安装EPEL仓库,再执行sudo yum install nginx。安装完成后,启动服务并设置为开机自启。对于Apache,使用sudo systemctl start apache2(Ubuntu)或sudo systemctl start httpd(CentOS);对于Nginx,使用sudo systemctl start nginx。然后通过curl http://localhost或浏览器访问服务器IP,查看默认欢迎页面以验证安装是否成功。
开放HTTP(端口80)和HTTPS(端口443)流量。Ubuntu/Debian系统使用sudo ufw allow 80,443/tcp;CentOS/RHEL系统使用sudo firewall-cmd --permanent --add-service={http,https},之后执行sudo firewall-cmd --reload。
若需托管多个网站,可在Apache的/etc/apache2/sites-available/目录或Nginx的/etc/nginx/conf.d/目录中创建配置文件,根据需求设置域名、根目录等参数,然后启用虚拟主机并重新加载服务配置。