martes, 10 de mayo de 2016

Virtualizar Hosting dentro de servidores de una red interna con Apache


Virtualizar Hosting dentro de servidores de una red interna

 
Paso Paso Apache en Centos:
http://www.ktaris.com/centos-virtual-hosts-apache/

Paso 1. Crear los directorios de los hosts virtuales

Primeramente se deben crear los directorios para cada uno de los dominios que van a estar alojados en el servidor, ahora compartido. El comando mkdir crea un directorio, y el argumento -p se encarga de crear todos los directorios intermedios si éstos no existen.
# Primer directorio.
sudo mkdir -p /var/www/ejemplo1.com/public_html
# Segundo directorio.
sudo mkdir -p /var/www/ejemplo2.com/public_html
Para realizar estas pruebas necesitarás acceso a un dominio real al que tengas acceso, para ver cómo se despliega información diferente con cada dominio o subdominio apuntado, pero eso será más adelante.

Paso 2. Permisos

Es necesario cambiar los permisos para que el servidor pueda leer los archivos (y escribir en caso de que la aplicación necesite subir archivos):
# Primer directorio.
sudo chown -R apache:apache /var/www/ejemplo1.com/public_html
# Segundo directorio.
sudo chown -R apache:apache /var/www/ejemplo2.com/public_html
Y para configurar los permisos de lectura, añadimos:
sudo chmod 755 /var/www

Paso 3. Crear contenido de prueba para mostrar

En este paso se crea el contenido que va a ir en el sitio o aplicación web. Para asegurarnos de que todo funciona, sin embargo, primeramente creamos un simple archivo de texto que identifique cada uno de los hosts virtuales. El contenido del archivo de prueba sería:
1
2
3
4
5
6
7
8
9
<html>
    <head>
        <title>Página de ejemplo</title>
    </head>
    <body>
        <h1>¡Saludos desde el host virtual!</h1>
        <h2>(El cual es ejemplo1.com)</h2>
    </body>
</html>
Para crear el archivo de prueba se puede utilizar el editor nano o vi, con el siguiente comando:
# Para vi:
sudo vi /var/www/ejemplo.com/public_html/index.html
#Para nano:
sudo nano /var/www/ejemplo.com/public_html/index.html
Y se repite la misma operación para el segundo hosts (y los sucesivos). No te olvides de cambiar el texto en el archivo de muestra, para saber si efectivamente se muestra contenido diferente para cada host virtual.

Paso 4. Activar los hosts virtuales

Primero, abrimos el archivo a editar:
sudo nano /etc/httpd/conf/httpd.conf
Al final del archivo (en serio, hasta el final) vienen los detalles de la configuración de hosts virtuales, y se ve algo así como lo mostrado en el listado 1.
Listado 1. Configuración de virtual hosts (sin alterar).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#
# Use name-based virtual hosting.
#
#NameVirtualHost *:80
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
# SSL protocol.
#   
 
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for requests without a known
# server name.
#
#<VirtualHost *:80>
#    ServerAdmin webmaster@ dummy-host.example.com
#    DocumentRoot /www/docs/dummy-host.example.com
#    ServerName dummy-host.example.com
#    ErrorLog logs/dummy-host.example.com-error_log
#    CustomLog logs/dummy-host.example.com-access_log common
#</VirtualHost>
Las líneas marcadas (la 4 y de 17 a 23) son aquellas que deben estar activas, para lo que se elimina el # al inicio (todas las demás permanecen igual). La acción ocurre en las líneas 17 a 23, que hacen los siguiente:
  • Las líneas 17 y 23 marcan el inicio y el final de la declaración de un host virtual.
  • ServerAdmin es el correo que se envía a los clientes en caso de error. Es decir, para que sepan a quién contactar en caso de error.
  • DocumentRoot hace referencia al lugar donde están ubicados los documentos. En este caso, es el directorio creado en el paso 1.
  • ServerName almacena el nombre del host virtual (es decir, ante qué nombre responderá en caso de que haya una llamada).
  • ErrorLog y CustomLog sirven para almacenar datos concernientes a errores en el servidor
Una configuración de ejemplo, eliminando los parámetros de cambio de ubicación para las bitácoras (logs), sería:
Listado 2. Configuración para dos hosts virtuales.
1
2
3
4
5
6
7
8
9
10
11
12
13
# Host virtual 1.
<VirtualHost *:80>
    ServerAdmin contacto@ ejemplo1.com
    DocumentRoot /var/www/ejemplo1.com/public_html
    ServerName ejemplo1.com
</VirtualHost>
 
# Host virtual 2.
<VirtualHost *:80>
    ServerAdmin contacto@ ejemplo2.com
    DocumentRoot /var/www/ejemplo2.com/public_html
    ServerName ejemplo2.com
</VirtualHost>
Tras terminar la configuración del servidor, reiniciamos el servidor de Apache:
sudo /etc/init.d/httpd restart
el cual ya estará listo para servir dos páginas o aplicaciones diferentes desde un solo servidor.


 /////////////////////////////////////******************************/////////////////////
Virtualizar Hosting dentro de servidores de una red interna
 
https://httpd.apache.org/docs/current/vhosts/examples.html
  

IP-based virtual hosting

The server has two IP addresses (172.20.30.40 and 172.20.30.50) which resolve to the names www.example.com and www.example.org respectively.
Listen 80

<VirtualHost 172.20.30.40>
    DocumentRoot "/www/example1"
    ServerName www.example.com
</VirtualHost>

<VirtualHost 172.20.30.50>
    DocumentRoot "/www/example2"
    ServerName www.example.org
</VirtualHost>




Otros enlaces interesantes:
https://www.digitalocean.com/community/tutorials/como-configurar-virtual-host-de-apache-en-ubuntu-14-04-lts-es
http://www.tecmint.com/apache-ip-based-and-name-based-virtual-hosting/

/////////////////////////****************************//////////////////////////////*******************/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

<-

VirtualHost Examples

Available Languages:  en  |  fr  |  ja  |  ko  |  tr 
This document attempts to answer the commonly-asked questions about setting up virtual hosts. These scenarios are those involving multiple web sites running on a single server, via name-based or IP-based virtual hosts.
top

Running several name-based web sites on a single IP address.

Your server has a single IP address, and multiple aliases (CNAMES) point to this machine in DNS. You want to run a web server for www.example.com and www.example.org on this machine.

Note

Creating virtual host configurations on your Apache server does not magically cause DNS entries to be created for those host names. You must have the names in DNS, resolving to your IP address, or nobody else will be able to see your web site. You can put entries in your hosts file for local testing, but that will work only from the machine with those hosts entries.
# Ensure that Apache listens on port 80
Listen 80
<VirtualHost *:80>
    DocumentRoot "/www/example1"
    ServerName www.example.com
  
    # Other directives here
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/www/example2"
    ServerName www.example.org

    # Other directives here
</VirtualHost>
The asterisks match all addresses, so the main server serves no requests. Due to the fact that the virtual host with ServerName www.example.com is first in the configuration file, it has the highest priority and can be seen as the default or primary server. That means that if a request is received that does not match one of the specified ServerName directives, it will be served by this first VirtualHost.

Note

You can, if you wish, replace * with the actual IP address of the system, when you don't care to discriminate based on the IP address or port.
However, it is additionally useful to use * on systems where the IP address is not predictable - for example if you have a dynamic IP address with your ISP, and you are using some variety of dynamic DNS solution. Since * matches any IP address, this configuration would work without changes whenever your IP address changes.
The above configuration is what you will want to use in almost all name-based virtual hosting situations. The only thing that this configuration will not work for, in fact, is when you are serving different content based on differing IP addresses or ports.
top

Name-based hosts on more than one IP address.

Note

Any of the techniques discussed here can be extended to any number of IP addresses.
The server has two IP addresses. On one (172.20.30.40), we will serve the "main" server, server.example.com and on the other (172.20.30.50), we will serve two or more virtual hosts.
Listen 80

# This is the "main" server running on 172.20.30.40
ServerName server.example.com
DocumentRoot "/www/mainserver"

<VirtualHost 172.20.30.50>
    DocumentRoot "/www/example1"
    ServerName www.example.com
    
    # Other directives here ...
</VirtualHost>

<VirtualHost 172.20.30.50>
    DocumentRoot "/www/example2"
    ServerName www.example.org
    
    # Other directives here ...
</VirtualHost>
Any request to an address other than 172.20.30.50 will be served from the main server. A request to 172.20.30.50 with an unknown hostname, or no Host: header, will be served from www.example.com.
top

Serving the same content on different IP addresses (such as an internal and external address).

The server machine has two IP addresses (192.168.1.1 and 172.20.30.40). The machine is sitting between an internal (intranet) network and an external (internet) network. Outside of the network, the name server.example.com resolves to the external address (172.20.30.40), but inside the network, that same name resolves to the internal address (192.168.1.1).
The server can be made to respond to internal and external requests with the same content, with just one VirtualHost section.
<VirtualHost 192.168.1.1 172.20.30.40>
    DocumentRoot "/www/server1"
    ServerName server.example.com
    ServerAlias server
</VirtualHost>
Now requests from both networks will be served from the same VirtualHost.

Note:

On the internal network, one can just use the name server rather than the fully qualified host name server.example.com.
Note also that, in the above example, you can replace the list of IP addresses with *, which will cause the server to respond the same on all addresses.
top

Running different sites on different ports.

You have multiple domains going to the same IP and also want to serve multiple ports. The example below illustrates that the name-matching takes place after the best matching IP address and port combination is determined.
Listen 80
Listen 8080

<VirtualHost 172.20.30.40:80>
    ServerName www.example.com
    DocumentRoot "/www/domain-80"
</VirtualHost>

<VirtualHost 172.20.30.40:8080>
    ServerName www.example.com
    DocumentRoot "/www/domain-8080"
</VirtualHost>

<VirtualHost 172.20.30.40:80>
    ServerName www.example.org
    DocumentRoot "/www/otherdomain-80"
</VirtualHost>

<VirtualHost 172.20.30.40:8080>
    ServerName www.example.org
    DocumentRoot "/www/otherdomain-8080"
</VirtualHost>
top

IP-based virtual hosting

The server has two IP addresses (172.20.30.40 and 172.20.30.50) which resolve to the names www.example.com and www.example.org respectively.
Listen 80

<VirtualHost 172.20.30.40>
    DocumentRoot "/www/example1"
    ServerName www.example.com
</VirtualHost>

<VirtualHost 172.20.30.50>
    DocumentRoot "/www/example2"
    ServerName www.example.org
</VirtualHost>
Requests for any address not specified in one of the <VirtualHost> directives (such as localhost, for example) will go to the main server, if there is one.
top

Mixed port-based and ip-based virtual hosts

The server machine has two IP addresses (172.20.30.40 and 172.20.30.50) which resolve to the names www.example.com and www.example.org respectively. In each case, we want to run hosts on ports 80 and 8080.
Listen 172.20.30.40:80
Listen 172.20.30.40:8080
Listen 172.20.30.50:80
Listen 172.20.30.50:8080

<VirtualHost 172.20.30.40:80>
    DocumentRoot "/www/example1-80"
    ServerName www.example.com
</VirtualHost>

<VirtualHost 172.20.30.40:8080>
    DocumentRoot "/www/example1-8080"
    ServerName www.example.com
</VirtualHost>

<VirtualHost 172.20.30.50:80>
    DocumentRoot "/www/example2-80"
    ServerName www.example.org
</VirtualHost>

<VirtualHost 172.20.30.50:8080>
    DocumentRoot "/www/example2-8080"
    ServerName www.example.org
</VirtualHost>
top

Mixed name-based and IP-based vhosts

Any address mentioned in the argument to a virtualhost that never appears in another virtual host is a strictly IP-based virtual host.
Listen 80
<VirtualHost 172.20.30.40>
    DocumentRoot "/www/example1"
    ServerName www.example.com
</VirtualHost>

<VirtualHost 172.20.30.40>
    DocumentRoot "/www/example2"
    ServerName www.example.org
</VirtualHost>

<VirtualHost 172.20.30.40>
    DocumentRoot "/www/example3"
    ServerName www.example.net
</VirtualHost>

# IP-based
<VirtualHost 172.20.30.50>
    DocumentRoot "/www/example4"
    ServerName www.example.edu
</VirtualHost>

<VirtualHost 172.20.30.60>
    DocumentRoot "/www/example5"
    ServerName www.example.gov
</VirtualHost>
top

Using Virtual_host and mod_proxy together

The following example allows a front-end machine to proxy a virtual host through to a server running on another machine. In the example, a virtual host of the same name is configured on a machine at 192.168.111.2. The ProxyPreserveHost On directive is used so that the desired hostname is passed through, in case we are proxying multiple hostnames to a single machine.
<VirtualHost *:*>
    ProxyPreserveHost On
    ProxyPass "/" "http://192.168.111.2/"
    ProxyPassReverse "/" "http://192.168.111.2/"
    ServerName hostname.example.com
</VirtualHost>
top

Using _default_ vhosts

_default_ vhosts for all ports

Catching every request to any unspecified IP address and port, i.e., an address/port combination that is not used for any other virtual host.
<VirtualHost _default_:*>
    DocumentRoot "/www/default"
</VirtualHost>
Using such a default vhost with a wildcard port effectively prevents any request going to the main server.
A default vhost never serves a request that was sent to an address/port that is used for name-based vhosts. If the request contained an unknown or no Host: header it is always served from the primary name-based vhost (the vhost for that address/port appearing first in the configuration file).
You can use AliasMatch or RewriteRule to rewrite any request to a single information page (or script).

_default_ vhosts for different ports

Same as setup 1, but the server listens on several ports and we want to use a second _default_ vhost for port 80.
<VirtualHost _default_:80>
    DocumentRoot "/www/default80"
    # ...
</VirtualHost>

<VirtualHost _default_:*>
    DocumentRoot "/www/default"
    # ...
</VirtualHost>
The default vhost for port 80 (which must appear before any default vhost with a wildcard port) catches all requests that were sent to an unspecified IP address. The main server is never used to serve a request.

_default_ vhosts for one port

We want to have a default vhost for port 80, but no other default vhosts.
<VirtualHost _default_:80>
DocumentRoot "/www/default"
...
</VirtualHost>
A request to an unspecified address on port 80 is served from the default vhost. Any other request to an unspecified address and port is served from the main server.
Any use of * in a virtual host declaration will have higher precedence than _default_.
top

Migrating a name-based vhost to an IP-based vhost

The name-based vhost with the hostname www.example.org (from our name-based example, setup 2) should get its own IP address. To avoid problems with name servers or proxies who cached the old IP address for the name-based vhost we want to provide both variants during a migration phase.
The solution is easy, because we can simply add the new IP address (172.20.30.50) to the VirtualHost directive.
Listen 80
ServerName www.example.com
DocumentRoot "/www/example1"

<VirtualHost 172.20.30.40 172.20.30.50>
    DocumentRoot "/www/example2"
    ServerName www.example.org
    # ...
</VirtualHost>

<VirtualHost 172.20.30.40>
    DocumentRoot "/www/example3"
    ServerName www.example.net
    ServerAlias *.example.net
    # ...
</VirtualHost>
The vhost can now be accessed through the new address (as an IP-based vhost) and through the old address (as a name-based vhost).
top

Using the ServerPath directive

We have a server with two name-based vhosts. In order to match the correct virtual host a client must send the correct Host: header. Old HTTP/1.0 clients do not send such a header and Apache has no clue what vhost the client tried to reach (and serves the request from the primary vhost). To provide as much backward compatibility as possible we create a primary vhost which returns a single page containing links with an URL prefix to the name-based virtual hosts.
<VirtualHost 172.20.30.40>
    # primary vhost
    DocumentRoot "/www/subdomain"
    RewriteEngine On
    RewriteRule "." "/www/subdomain/index.html"
    # ...
</VirtualHost>

<VirtualHost 172.20.30.40>
DocumentRoot "/www/subdomain/sub1"
    ServerName www.sub1.domain.tld
    ServerPath "/sub1/"
    RewriteEngine On
    RewriteRule "^(/sub1/.*)" "/www/subdomain$1"
    # ...
</VirtualHost>

<VirtualHost 172.20.30.40>
    DocumentRoot "/www/subdomain/sub2"
    ServerName www.sub2.domain.tld
    ServerPath "/sub2/"
    RewriteEngine On
    RewriteRule "^(/sub2/.*)" "/www/subdomain$1"
    # ...
</VirtualHost>
Due to the ServerPath directive a request to the URL http://www.sub1.domain.tld/sub1/ is always served from the sub1-vhost.
A request to the URL http://www.sub1.domain.tld/ is only served from the sub1-vhost if the client sent a correct Host: header. If no Host: header is sent the client gets the information page from the primary host.
Please note that there is one oddity: A request to http://www.sub2.domain.tld/sub1/ is also served from the sub1-vhost if the client sent no Host: header.
The RewriteRule directives are used to make sure that a client which sent a correct Host: header can use both URL variants, i.e., with or without URL prefix.
Available Languages:  en  |  fr  |  ja  |  ko  |  tr 
top

Comments

Notice:
This is not a Q&A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed again by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Freenode, or sent to our mailing lists.

RSS   Log in / register

Ghinea Andrei 2 days ago Rating: 0 (register an account in order to rate comments)
I tried this things, but it didn't worked for me (okay it worked to enter the site trough the name that I entered), but the thing is that I don't know how to make it to be accessible to the other people. For example if I want to put this page online, it works if I give my ip to my friend, but when I give him the domain name it's not working .... Can someone help me ?
Ghinea Andrei 2 days ago Rating: 0 (register an account in order to rate comments)
PS: I'm using the 2.4 version, because the newer version is not working for me ....
Schmidt-G�tter 451 days ago Rating: 0 (register an account in order to rate comments)
Default virtual hosts: Leaving out "ServerName" seems not a good idea because of unwanted side effects. It is much better to declare a non-existing hostname. See for example following configuration: <VirtualHost *:80> # Commenting out following line will stop "host_b.de" from matching / working: ServerName non.existing_host.noTld DocumentRoot /var/www/default </VirtualHost> <VirtualHost *:80> Servername host_a.de DocumentRoot /var/www/host_a </VirtualHost> <VirtualHost *:80> Servername host_b.de DocumentRoot /var/www/host_b </VirtualHost> This works so far. But commenting out "ServerName" inside the first (default) vhost effectively will stop the last vhost: Requests like http : // host_b . de/ are being handled by the default host in that case. (This may in fact be a bug in Apache 2.4 or a documentation issue. I don't know...)
Schmidt-G�tter 451 days ago Rating: 0 (register an account in order to rate comments)
A short addition: Reverse DNS of my Server IP does result in "host_b.de".
meeeeh 445 days ago Rating: 0 (register an account in order to rate comments)
Well, the reason for that is simple: Wrong order. Also, your "fix" is wrong: If you specify a non existing server name, your virtual host will never match. What you need to do in this case is move the general matching (i.e. matches all remaining domains) below all specific matchings. 1.) host definition: ServerName host_a.de 2.) host definition: ServerName host_b.de 3.) host definition: no server name This is due to the fact that apache takes the first host that applies. Since your servername-less host applies for any request, all hosts specified after it will be ignored.
covener 445 days ago Rating: +1 (register an account in order to rate comments)
The a set of name based vhosts, the first listed VH is the default VH. If you omit the servername, it could be inherited/calculated from the base or from your OS hostname (which is what OP is experiencing)
Slawek 1246 days ago Rating: 0 (register an account in order to rate comments)
"Name-based hosts on more than one IP address." section has "172.20.30.50" as the IP address for both virtual hosts -- the first one probably should be 172.20.30.40
Sling 1191 days ago Rating: 0 (register an account in order to rate comments)
The point being explained there, is that when the server listens on both IP's and there is no VirtualHost matching one of the IP's, requests to that IP will be handled by the (default) ServerName + DocumentRoot specified outside of the virtualhost scopes.

No hay comentarios:

Publicar un comentario