CentOS7 Apache实现多域名配置

2026-04-14 01:50:07 203
分类:Linux

参考:

https://blog.csdn.net/qq_36731677/article/details/59120589

http://blog.51cto.com/13525470/2070375

主配置文件: vi /etc/httpd/conf/httpd.conf

在httpd服务程序主配置文件中最为常用的参数包括有:

ServerRoot服务目录
ServerAdmin管理员邮箱
User运行服务的用户
Group运行服务的用户组
ServerName网站服务器的域名
DocumentRoot网站数据目录
Listen监听的IP地址与端口号
DirectoryIndex默认的索引页页面
ErrorLog错误日志文件
CustomLog访问日志文件
Timeout网页超时时间,默认为300秒.
Include需要加载的其他文件

一、Apache(httpd)安装 

安装

yum install httpd

设置自启

systemctl enable httpd.service

二、软件配置 

编辑httpd.conf就够了,httpd.conf在/etc/httpd/conf中

vim /etc/httpd/conf/httpd.conf

1、用#注释掉以下两行(其实如果不注释,好像没有什么影响)

#ServerName www.example.com
#DocumentRoot /var/www/html

2、开放目录使用权限 

在httpd.conf中写入,引号中的路径是自定义的开放访问的路径,其子目录也开放使用。 

如果不写这个段落,网页会被重定向到默认页面,虚拟主机中的自定义路径设置无效。 

Directory里的东西必修要写,不写就打不开。。。亲测

<Directory "/home/www">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

3、写入虚拟主机信息 

①开启虚拟主机并确定其监听的主机名与端口,* 表示省略,80为网页默认端口。

NameVirtualHost *:80

②写入单个虚拟主机信息 

ServerName —— 主机名(域名或公网IP) 

ServerAlias —— 别名(二级域名或其他域名或IP) 

DocumentRoot —— 文件目录(表示将域名映射至该文件目录)。 

按照模版有几个写几个,不知道有没有上限。。。 

虚拟主机的文件目录必须在上述的开放访问的目录下,不然无法访问。 

模版:

<VirtualHost *:80>
    ServerName XXX
    ServerAlias XXX2
    DocumentRoot /XXX
</VirtualHost>

完整过程 

二、示例仅供参考,如有其他需要,请根据情况自行修改。 

1、控制台命令

yum install httpd
systemctl enable httpd.service
systemctl start httpd.service
vim /etc/httpd/conf/httpd.conf

2、httpd.conf修改(略去不用修改的部分)

#ServerName www.example.com
#DocumentRoot /var/www/html
<Directory "/home/www">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>
NameVirtualHost *:80
<VirtualHost *:80>
    ServerName www.mywebsite1.com
    DocumentRoot /home/www/htmla
</VirtualHost>
<VirtualHost *:80>
    ServerName mywebsite1.com
    DocumentRoot /home/www/htmlb
</VirtualHost>
<VirtualHost *:80>
    ServerName www.mywebsite2.com
    ServerAlias mywebsite2.com
    DocumentRoot /home/www/htmlc
</VirtualHost>

# 端口方式
Listen 8081
Listen 8082
<VirtualHost *:8081>
DocumentRoot "/home/www/blog"
	<Directory "/home/www/blog">
		Options Indexes FollowSymLinks
		AllowOverride All
		Order allow,deny
    Allow from all
		Require all granted
	</Directory>
</VirtualHost>

<VirtualHost *:8082>
DocumentRoot "/home/www/lab"
	<Directory "/home/www/lab">
		Options Indexes FollowSymLinks
		AllowOverride All
		Order allow,deny
    Allow from all
		Require all granted
	</Directory>
</VirtualHost>

也可以在末尾添加

Include conf/vhosts.conf

将多域名配置写在在vhots.conf。

其它注意事项:

如果无法访问,需要关闭防火墙、关闭selinux。开启网站目录读写权限