The Blog Vhosts, SSL et modification fichier hosts sur Mac en 1 tour de main
Rédigé le 10/03/2024
Par Xavier

Dans la lignée du post sur le serveur web pour Mac, voici un petit script Shell pour ceux qui ont déjà leur écosystème en place afin de facilement créer les fichiers vhosts, SSL et modifier le fichier hosts de votre mac ;)

C'est toujour un peu long, à chaque nouveau projet, de lancer son terminal et de créer à la main le fichier hosts, les fichiers SSL et de modifier le fichier hosts du Mac.

Pas de panique...

Voici un petit script shell tout bête qui le fait pour vous !!!

créez un fichier là ou bon vous semble sur votre Mac (n'allez tout de même pas le coller au fin fond d'un obscur dossier système ;)

Collez le code ci dessous dans le fichier et enregistrez le sous le nom que vous aurez décidé (pour ma part et pour le reste de ce post ce sera manage.sh) !

#!/bin/sh

# path to www folder
workpath=""
# extention for local domains
extention="" # eg: local (without dot)
# vars for SSL
country=""                     # country iso code (FR for France)
state=""                # region for France or state
locality=""             # your locality
organisation=""          # your organisation name
organisationalUnit=""          # your organisation unit eg: IT or DEVELOPMENT ...
email="" # your email address
password=""             # your Mac root password for sudo and SSL
# path to SSL folder to store certificates
sslPath=""
# path to vhosts folder
virtualPath=""
# local IP
ip=""

PS3="Setup or remove a local domain ?: "
items=("Setup" "Remove" "Quit")

select resp in "${items[@]}"
do
    case $resp in
    "Setup")
        while true; do
            read -p "Enter the domain name (without extension and www) :" domain
            if [ -z $domain ]; then
                echo "The domaine is mandatory..."
                continue
            fi
            break
        done
        while true; do
            read -p "Enter the projet folder name (for localhost just a dot '.'):" workingDir
            if [ -z $workingDir ]; then
                echo "The projet directory is mandatory..."
                continue
            fi
            break
        done
        while true; do
            read -p "Enter the DocumentRoot if different of your project folder name (eg: for Symfony ou Laravel is public), else just a dot '.' :" docRoot
            if [ -z $docRoot ]; then
                echo "The DocumentRoot is mandatory..."
                continue
            fi
            break
        done

        if [ "$docRoot" == "." ]; then
            newpath="$workpath/$workingDir"
        else
            newpath="$workpath/$workingDir/$docRoot"
        fi

        if [ "$domain" != "localhost" ]; then
            newDomain="$domain.$extention"
        else
            newDomain=$domain
            newpath=$workpath
        fi

        cd $sslPath

        echo "Générate SSL Key for $newDomain"
        openssl genrsa -out $newDomain.key 2048

        openssl rsa -in $newDomain.key -passin pass:$password -out $newDomain.key

        openssl req -new -key $newDomain.key -out $newDomain.csr -passin pass:$password \
            -subj '/C='$country'/ST='$state'/L='$locality'/O='$organisation'/OU='$organisationalUnit'/CN='$organisation'/emailAddress='$email''

        echo " authorityKeyIdentifier=keyid,issuer
            basicConstraints=CA:FALSE
            keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
            subjectAltName = @alt_names
            [alt_names]
            DNS.1 = "$domain > $newDomain.ext
        sed -i '' 's|domain|'$newDomain'|g' $newDomain.ext

        openssl x509 -req -in $newDomain.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial \
            -out $newDomain.crt -days 825 -sha256 -extfile $newDomain.ext

        mkdir $newpath/logs
        chmod 777 $newpath/logs
        cd $virtualPath

        echo '
                DocumentRoot "'$newpath'"
                ServerName '$newDomain'
                ServerAlias www.'$newDomain'
                ErrorLog "'$newpath'/logs/'$newDomain'-error_log"
                
                    Options Indexes FollowSymLinks MultiViews
                    AllowOverride All
                    Order allow,deny
                    allow from all
                
            

            
                ServerName '$newDomain'
                ServerAlias www.'$newDomain'
                DocumentRoot "'$newpath'"
                ErrorLog "'$newpath'/logs/'$newDomain'-error_log"

                SSLEngine on
                SSLCertificateFile "'$sslPath'/'$newDomain'.crt"
                SSLCertificateKeyFile "'$sslPath'/'$newDomain'.key"
                
                    Options Indexes FollowSymLinks MultiViews
                    AllowOverride All
                    Order allow,deny
                    allow from all
                
            ' > $newDomain.conf

        touch $newpath/logs/$newDomain-error_log
        chmod 777 $newpath/logs/$newDomain-error_log

        if [ "$domain" != "localhost" ]; then
            cd /private/etc

            echo "" | sudo tee -a hosts
            echo "$ip "$newDomain | sudo tee -a hosts
            echo "$ip www."$newDomain | sudo tee -a hosts
            echo "::1	"$newDomain | sudo tee -a hosts
            echo "::1	www."$newDomain | sudo tee -a hosts
        fi

        sudo killall -HUP mDNSResponder
        sudo apachectl restart
        echo "Bravo !!! "
        echo "You can now access to your local domain by enter https://$newDomain in your browser !"
        break
        ;;
    "Remove")
        while true; do
            read -p "Enter domain name (without extension and www) :" domain
            if [ -z $domain ]; then
                echo "The domaine is mandatory..."
                continue
            fi
            break
        done
        
        rm $sslPath/$domain.$extention.key
        rm $sslPath/$domain.$extention.csr
        rm $sslPath/$domain.$extention.crt
        rm $sslPath/$domain.$extention.ext
        echo "SSL files removed : OK"
        rm $virtualPath/$domain.$extention.conf
        echo "Apache configuration file removed : OK"

        cd /private/etc
        sudo sed -i".bak" "/$domain/d" hosts
        sudo sed -i '' '/^$/d' hosts
        sudo rm hosts.bak
        echo "Hosts file entries removed : OK"
        echo "Nexr : you can delete your project folder" 
        break
        ;;
    "Quit")
        echo "Au revoir, Bye, Ciao ;-)"
        break
        ;;
    *)
        echo "Thanks to select an action to do"
        ;;
    esac
done

Renseignez ensuite les variables en haut du fichier :

  • workpath => path de votre dossier de travail
  • extention => extension que vous utilisez en local (eg. .localou .dev)
  • country => code ISO à 2 lettres de votre pays (FR pour la France par exemple)
  • state => nom du département ou de la région (optionnel)
  • organisation => Nom de votre entreprise (optionnel)
  • organisationalUnit => service dans votre entreprise (optionnel)
  • email => votre adresse email
  • sslPath => path vers le dossier des fichiers SSL
  • virtualPath => path vers le dossier des vhosts
  • ip => adresse IP utilisée pour accéder aux projets (normalement 127.0.0.1)

Avec votre terminal, allez ensuite dans le dossier ou se situ le script puis saisissez ces commandes :

sudo chmod 755 manage.sh

Une fois votre fichier exécutable, il vous suffira de venir dans le dossier avec le terminal et de faire 

./manage.sh

A partir de maintenant il ne vous reste plus qu'à suivre les instructions, comme celles indiquées dans mon précédent article sur le serveur web pour Mac

Ce n'est pas plus comliqué ;)

Laissez un commentaire