Multi-domain in Apache without any hassle on the local host

    The Internet is full of guides for setting up virtual hosts in Apache. But, in most cases, creating such a subdomain is a troublesome affair.
    According to the "standard" instructions it is proposed to do the following:
    1. Create a folder for the site
    2. Create a configuration file with the name of the future domain
    3. Enable the site with a special option
    4. Reload Apache
    5. Register our domain in the hosts file

    Some try to optimize this process with various scripts, but this, in essence, does not solve the problem.
    So, let's try to ensure that the process of creating a subdomain is reduced only to creating a folder for the site. Is it possible? We
    ’ll check ... I won’t tell you how to install LAMP, since you most likely can do it with your eyes closed (smile). Let's move on to the most interesting.

    Vhost_alias setting


    Turn on the vhost_alias module . He will be the main character.
    sudo a2enmod vhost_alias

    We include, if necessary, mod_rewrite .
    sudo a2enmod rewrite

    Open the httpd.conf file and proceed with the direct configuration.
    #Подставляем имя сервера из заголовка запроса пользователя
    UseCanonicalName Off
    # Формируем логи так, чтобы в них указывалось имя виртуального хоста
    LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
    CustomLog /home/%username%/web/access_log vcommon
    # Нужно для работы mod_rewrite
    
        Options FollowSymLinks
        AllowOverride All
    
    # Собственно правило, по которому будет искаться нужный нам сайт
    VirtualDocumentRoot /home/%username%/web/%-2 

    % -2 means that the host will be selected by the penultimate part of the domain name. In other words, by creating the directory / home /% username% / web / habrahabr , we can access it as habrahabr.ru (or habrahabr.com , or even habrahabr.xxx ).
    You can also set your own host name selection options:
    • % 0 Full name
    • % 1 First part of the name
    • % 2 Second part of the name
    • % 3 The third part of the name
    • % -1 last part
    • % -2 penultimate part
    • % 2 + Second and all subsequent parts
    • % -2 + The penultimate and all subsequent parts

    Restart Apache.
    sudo service apache2 restart

    Our server is already running. We can verify this by creating a folder with the desired name, for example test, and placing index.php with some contents, for example, " " there.
    Oh yes, you still need to register our domain in the / etc / hosts file .
    127.0.0.1    test.loc

    Everything, now you can open the page in the browser.
    Stop, we didn’t agree! Creating a site should be reduced to creating a directory for it. Well then, let's do ...

    DNS server setup


    For this, we will use the bind9 DNS server . All domains with the suffix * .loc will look at our local machine.
    Install the DNS server
    sudo apt-get install bind9

    Open the named.conf.options configuration file and add
    acl "home" {192.168.1.0/24; 127.0.0.1;};
    options {
        directory "/var/cache/bind";
        auth-nxdomain no;
        listen-on-v6 { none; };
        listen-on { 127.0.0.1; };
        allow-transfer { none; };
        allow-query {"home";};
        forward first;
        # Указываем DNS-адреса провайдера
        forwarders {
            192.168.1.2;
            8.8.8.8;
        };
    }; 

    We create files for a domain zone.
    cd /etc/bind/
    sudo touch db.loc

    Db.loc content
    $TTL 86400
    $ORIGIN loc.
    @ IN SOA skywrtr.loc. admin.skywrtr.loc. (
        2010050100; Serial
        14400; Refresh
        7200; Retry
        3600000; Expire
        86400 ); Minimum
    @ IN NS localhost.
    * IN A 127.0.0.1 


    Finally, open the named.conf.local file and append it there.
    zone "loc" {
        type master;
        file "/etc/bind/db.loc";
        allow-transfer { 127.0.0.1; };
        notify no;
    }; 


    Remain connected to our DNS server. Or through the /etc/resolv.conf file , adding a line
    nameserver 127.0.0.1

    or through a standard network connection manager. In the connection properties, on the "IPv4 Settings" tab, add the address 127.0.0.1 in the "DNS Servers" field.



    For convenience, create a local host for phpmyadmin
    ln -s /usr/share/phpmyadmin/ /home/alex/web/phpmyadmin

    It is now available at phpmyadmin.loc .

    Some notes


    There are a couple of notes on working with vhost_alias.
    • The variable $ _SERVER ['DOCUMENT_ROOT'] gives incorrect data , so you have to use either dirname (__ FILE__) or realpath () . It depends on what you need.
    • If mod_rewrite has stopped working, don't panic. In the .htaccess file after the line
      RewriteEngine    on

      Insert
      RewriteBase /


    Related links:
    httpd.apache.org/docs/2.0/en/vhosts/mass.html
    www.softtime.ru/info/apache.php?id_article=103

    PS Thanks to Wott for the kindly provided bind configs.

    Also popular now: