在Linux系统中,HTTP服务器的虚拟主机配置是高效利用服务器资源的关键技术,允许同一物理服务器托管多个独立网站。以Apache和Nginx为例,其配置流程如下:
Apache虚拟主机配置****
1.
安装与目录准备
通过apt-get install apache2(Debian/Ubuntu)或yum install httpd(RHEL/CentOS)安装Apache。在/var/www/下为每个虚拟主机创建独立目录,如/var/www/example.com/public_html,并设置权限为apache:apache。
2.
3.
配置文件创建
在/etc/apache2/sites-available/(Debian/Ubuntu)或/etc/httpd/conf.d/(RHEL/CentOS)目录下新建配置文件(如example.com.conf),核心配置如下:
4.
5.
apache
6.
7.
| <VirtualHost *:80> | |
|---|---|
| ServerName example.com | |
| ServerAlias www.example.com | |
| DocumentRoot /var/www/example.com/public_html | |
| ErrorLog ${APACHE_LOG_DIR}/example.com-error.log | |
| CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined | |
| <Directory /var/www/example.com/public_html> | |
| Require all granted | |
8.
9.
启用与重启
使用a2ensite example.com.conf启用配置(Debian/Ubuntu),或直接重启服务:systemctl restart apache2(Apache)或systemctl restart httpd(RHEL/CentOS)。
10.
Nginx虚拟主机配置****
1.
安装与目录准备
通过apt-get install nginx安装Nginx。目录结构与Apache类似,但配置文件路径为/etc/nginx/sites-available/example.com。
2.
3.
配置文件示例
4.
5.
nginx
6.
7.
| server { | |
|---|---|
| listen 80; | |
| server_name example.com www.example.com; | |
| root /var/www/example.com/public_html; | |
| index index.html; | |
| access_log /var/log/nginx/example.com-access.log; | |
| error_log /var/log/nginx/example.com-error.log; | |
| } |
8.
9.
启用与重启
创建符号链接:ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/,重启服务:systemctl restart nginx。
10.
关键注意事项****
· 域名解析:需在DNS服务商处将域名A记录指向服务器IP,或修改本地/etc/hosts文件测试。
· 防火墙配置:确保80/443端口开放,如firewall-cmd --add-service=http --permanent。
· 日志监控:通过tail -f /var/log/apache2/example.com-error.log实时排查问题。
· SELinux/AppArmor:若启用安全模块,需调整策略或目录上下文,如chcon -R -t httpd_sys_content_t /var/www/example.com。
通过上述步骤,可实现基于域名的虚拟主机隔离,提升服务器利用率与管理效率。