Cria ambiente virtual (VirtualHost no Apache e Virtual Mail no Postfix) para desenvolvimento web

Publicado por Alysson (última atualização em 28/07/2014)

[ Hits: 3.841 ]

Download webhost.sh




Cria um ambiente virtual completo para desenvolvimento web, com VirtualHost no Apache e Mail no Postfix.
É possível acompanhar melhorias no código no repositório:

- https://gist.github.com/LACabeza/90fe2174593fcad795c5

É preciso ter Apache 2 e Postfix instalados.
Depois, é preciso especificar o diretório de trabalho na variável workspace, o usuário na variável user e o grupo do Apache na variável group.

Para utilizar o script, execute

$ ./webhost.sh website.local

Onde "website" é o nome do ambiente virtual que será criado.

Com isso, o diretório workspace/website, quando não existir, será criado e suas permissões serão modificadas para dar acesso ao Apache.
Será adicionado no arquivo /etc/hosts a linha "website.local".
Será criado o VirtualHost no Apache: http://website.local
Será criado o Virtual Mail "webmaster@website.local" que encaminha as mensagens para o usuário especificado no script.

  



Esconder código-fonte

#!/bin/bash
# --------------------------------------------------------------------------- #
# @file
#   webhost.sh
#
#   Creates a virtual enviroment for web development.
#
# @author   Alysson Azevedo
# @link     http://lac.eti.br
# @license  http://www.gnu.org/licenses/gpl-2.0.html
#
#
# * This program is free software: you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation, either version 3 of the License, or
# * (at your option) any later version.
#
#   Requirements
#      apache2
#      postfix
#
#   Instructions
#   1º Set up your enviroment configs;
#      workspace=/home/user/workspace
#
#   2º Add your user on apache's group
#
#   3º Skip this step
#
#   4º Use this script
#
# --------------------------------------------------------------------------- #

# Workspace directory
workspace=/mnt/dataExt/Works/www

# Developer's user
user=viper

# Apache's group (make sure your user belongs to apache's group)
group=www-data

# How to use:
#   ./webhost.sh website.local

# What webhost.sh do:
#   First, the directory $workspace/website will be created if it doesn't exists, and its permission will be set
#   Then will be append a new line on /etc/hosts with the virtual host's name
#   After a virtual host will be created on apache (note that the apache virtual hosts configuration only allow localhost access)
#   And finally a virtual mail will created

# --------------------------------------------------------------------------- #

# First param must to be the virtual server's name
servername=$1

# Virtual server path
serverpath=$workspace/${servername/.local/} #remove .local

# Check privileges
[ `id -u` -ne 0 ] && {
    echo -e "Super user required. \nTry again using 'sudo $0'." >&2
    exit 1
}

# Check param
[ -z "$servername" ] && {
    echo -e "The virtualhost's name must be given. \nExample: $0 '$HOSTNAME.local'" >&2
    exit 2
}
# Check usage: ask for suffix to prevent accidental use
[ -n "`grep " " <<< $servername`" ] && {
    echo -e "Hostname cannot contain space characters. \nExample: $0 '$HOSTNAME.local'" >&2
    exit 3
}
# Check usage: ask for suffix to prevent accidental use
[ -z "`grep "\.local" <<< $servername`" ] && {
    echo -e "Suffix '.local' must be given. \nExample: $0 '$HOSTNAME.local'" >&2
    exit 3
}
# Check if serverpath isn't a file
[ -f $serverpath ] && {
    echo -e "$servername isn't a good name because there's a file '$serverpath'.\nTry another hostname." >&2
    exit 4
}

# Confirm operation
read -p "A virtualhost will be created for '$servername'.
Do you confirm the operation? [yes/no]: " confirm
[ "${confirm,,}" != yes ] && {
    echo "Leaving without change anything."
    exit
}

# All right, let's do this
echo "Applying changes."

# If serverpath doesn't exists, make it
[ ! -d $serverpath ] && {
    mkdir $serverpath
    chown $user:$group $serverpath
    echo "Directory '$serverpath' created."
}

# Set up the permissions
chgrp -R www-data $serverpath
chmod -R g+w $serverpath
find $serverpath -type d -print0 | xargs -0 chmod g+s
echo "Permissions for $serverpath modified."

# Update hosts file, if it's needed.
[ -z "`grep $servername /etc/hosts`" ] && {
    echo "
::1 $servername
::1 www.$servername" >> /etc/hosts
    echo "File /etc/hosts updated."
}

# Virtual hosts http://httpd.apache.org/docs/current/mod/core.html#virtualhost
# Create Apache2's VirtualHost, if it's needed
[ ! -f "/etc/apache2/sites-enabled/200-${servername/./-}.conf" ] && {
    echo "\
<VirtualHost *:80>
    ServerName $servername
    ServerAlias www.$servername

    ServerAdmin webmaster@$servername
    DocumentRoot $serverpath

    <Directory $serverpath/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/8
        Allow from ::1
        Allow from 192.168.56.0/24
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/error-${servername/.local/}.log
    CustomLog \${APACHE_LOG_DIR}/access-${servername/.local/}.log combined

</VirtualHost>" > /etc/apache2/sites-available/${servername/./-}.conf

    # Makes a symbol link from /etc/apache2/sites-available to /etc/apache2/sites-enabled
    ln -s "../sites-available/${servername/./-}.conf" "/etc/apache2/sites-enabled/200-${servername/./-}.conf"

    # Apply changes on apache
    service apache2 restart >&2

    echo "Virtualhost created. Visit: http://$servername"
}

# Virtual mails http://www.postfix.org/VIRTUAL_README.html
# Add host for postfix, if it's needed.
[ -z "`grep $servername /etc/postfix/virtual_domains.conf`" ] && {
    echo "$servername" >> /etc/postfix/virtual_domains.conf
    echo "File /etc/postfix/virtual_domains.conf updated."
}

# Add mail for postfix, if it's needed.
[ -z "`grep $servername /etc/postfix/virtual_aliases.conf`" ] && {
    echo "webmaster@$servername $user" >> /etc/postfix/virtual_aliases.conf
    postmap /etc/postfix/virtual_aliases.conf
    echo "Mail alias webmaster@$servername to $user was created."
}

echo "Done."

Scripts recomendados

Função que indica o estado do funcionamento do script

Converter Arquivo RMVB para AVI

EPD (Editor de Pacotes Debian)

Script para encontrar arquivos .wam, .mpeg

Script para fazer funcionar o bloqueio por horário - Squid


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts