To create a virtual host on CentOS 7 (using Apache HTTP Server), follow these step-by-step instructions:
1. Install Apache HTTP Server
First, update the system and install Apache:
sudo yum update -y
sudo yum install httpd -y
2. Start & Enable Apache
Ensure Apache runs on boot and starts immediately:
sudo systemctl start httpd
sudo systemctl enable httpd
3. Allow HTTP Through Firewall
Open port 80 (HTTP) in firewalld:
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload
4. Create Directory Structure
For a domain (e.g., example.com), create a root directory for your site:
sudo mkdir -p /var/www/example.com/public_html
5. Set Permissions
Grant ownership to your user (for editing files) and set correct permissions:
sudo chown -R $USER:$USER /var/www/example.com/public_html
sudo chmod -R 755 /var/www
6. Create a Test Page
Add a sample index.html to verify the site:
nano /var/www/example.com/public_html/index.html
Paste this content:
<h1>Welcome to example.com!</h1>
<p>Virtual host setup successful.</p>
Save and exit (Ctrl+O, Enter, Ctrl+X).
7. Configure Virtual Host
Create a config file for your domain in Apache’s conf.d directory:
sudo nano /etc/httpd/conf.d/example.com.conf
Add this virtual host block:
<VirtualHost *:80>
ServerAdmin webmaster@example.com
DocumentRoot /var/www/example.com/public_html
ServerName example.com
ServerAlias www.example.com
ErrorLog /var/log/httpd/example.com_error.log
CustomLog /var/log/httpd/example.com_access.log combined
</VirtualHost>
Save and exit.
8. Validate Apache Config
Check for syntax errors:
sudo apachectl configtest
If output is Syntax OK, proceed.
9. Fix SELinux Context
CentOS uses SELinux by default—allow Apache to access your site files:
sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/example.com/public_html(/.*)?"
sudo restorecon -Rv /var/www/example.com/public_html
10. Restart Apache
Apply changes:
sudo systemctl restart httpd
11. Test the Virtual Host
- Local Test: Edit
/etc/hoststo map your domain to localhost:sudo nano /etc/hostsAdd:
127.0.0.1 example.com www.example.com - Browser/CLI: Open
http://example.comin a browser or run:curl http://example.com
Note: For HTTPS, install Let’s Encrypt (via Certbot) and update the virtual host to use port 443.
This setup will host your site on example.com (or your domain) using Apache on CentOS 7. ✅
Let me know if you need help with HTTPS or troubleshooting!


作者声明:本文包含人工智能生成内容。