Virtual Hosts LAMP and Selinux on CentOS 6.3

Out of personal preference I always like to keep all my user files mounted on a separate partition within the /home directory, this is great for security and organization. Moving Apache web files to the home directory will cause Selinux to have a fit, and unfortunately many people’s solution is to simply disable Selinux simply because they don’t understand the raw power of what Selinux does.

So here’s a quick run down of how to get it running within minutes, the following assumes a new install (ie. no previous configs, as it will override some existing if they conflict). You are free to copy and paste the entire block without any issues. Don’t forget to modify the domain.com to your own domain

*This can be copy and pasted straight into terminal – just remember to change domain.com *

yum install httpd mysql mysql-server php php-mysql php-common php-pear php-mysql  
cat <<'EOF' > /etc/httpd/conf.d/vhosts.conf

NameVirtualHost *:80

<VirtualHost *:80>  
     ServerAdmin [email protected]
     ServerName domain.com
     ServerAlias www.domain.com
     DocumentRoot /home/.sites/_domain.com/public_html/
     ErrorLog /home/.sites/_domain.com/logs/error.log
     CustomLog /home/.sites/_domain.com/logs/access.log combined
</VirtualHost>

<VirtualHost *:80>  
     ServerAdmin [email protected]
     ServerName domain.net
     ServerAlias www.domain.net
     DocumentRoot /home/.sites/_domain.net/public_html/
     ErrorLog /home/.sites/_domain.net/logs/error.log
     CustomLog /home/.sites/_domain.net/logs/access.log combined
</VirtualHost>  
EOF

mkdir -p /home/.sites/domain.com/{public_html,logs}  
mkdir -p /home/.sites/domain.net/{public_html,logs}

# Apply Selinux Boolean
setsebool -P httpd_can_network_connect_db 1  
setsebool -P httpd_can_network_memcache 1  
setsebool -P httpd_enable_homedirs 1

chcon -R -t httpd_user_content_t /home/.sites/

service httpd start  
chkconfig httpd on  
service mysqld start  
chkconfig mysqld on  
mysql\_secure\_installation  

And you’re done!
If you’re managing all your sites through a separate user account other than root (which is what you should be doing), don’t forget to change the user/group permissions on the files:

chown andrew:webmasters -R /home/.sites/  
cd /home/.sites/  
find . -type f -exec chmod 644 {} \; && find . -type d -exec chmod 755 {} \;

# Allow Httpd to write to our log directory
setsebool -P httpd_unified=1  

Happy Hosting!

comments powered by Disqus