4.
HTTP standard
The following image shows the communication between the browser and the server. On
the one hand, the browser makes an HTTP request. The server then processes it and
sends an HTTP response accordingly.
To better understand the sequence of events that make up an HTTP transaction, let's see
it with an example. Suposse the user types the following URL into the browser,
http://www.example.com/status.php
The browser parses this URL and generates the following HTTP request, that is sent to
the server:
GET /status.php HTTP/1.1
Accept: image/gif, image/png, image/jpeg, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; .NET CLR 1.1.4322)
Host: www.example.com
Connection: Keep-Alive
When a Web server receives a request like this, it looks for the information that is
represented by /status.php. If the information actually exists on the server, it send it back
to the client (browser) as follows, HTTP response:
HTTP/1.1 200 OK
Date: Mon, 08 Dec 2003 16:46:40 GMT
Server: Apache/1.3.27 (Unix) mod_throttle/3.1.2 PHP/4.3.2
X-Powered-By: PHP/4.3.2
X-Accelerated-By: PHPA/1.3.3r2
Connection: close
Content-Type: text/html; charset=utf-8
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
[REST OF WEB PAGE OMITTED FOR SPACE REASONS]
1
According to the HTTP standard, the web client can request several operations from the
server, called HTTP methods:
Methods Description
GET To get server information. This operation is executed every time a link is
clicked to access a web page.
(To request a resource from the server)
POST To send information from the client to the web server. For example, data
entered into a web form.
HEAD Similar to GET, but only the header of the page is requested, with
information such as size, type, modification date, etc.
(To request information about a resource)
...
Regarding response codes, status codes that the server sends indicating the result of the
request, these are the codes that are usually seen when the browser cannot display the
requested web page. The syntax of an HTTP response is a status line that has a fixed
structure where the protocol version, the error code and an explanatory text are indicated.
The possible status codes are identified by three-digit numbers and classified into five
groups:
Status codes Description
1xx - Informational responses Informational codes.
2xx - Succesful responses Codes of success in the request.
3xx - Redirection messages Codes to re-address the request.
4xx - Client error responses Codes due to an error generated on the client.
5xx - Server error responses Codes due to errors generated on the server.
The most typical responses are the codes '200 OK', to indicate the confirmation of the
request, and the '404 Not Found. The server has not found anything matching the
Request-URI', to indicate that the requested object is not found available.
La imatge següent mostra la comunicació entre el navegador i el servidor. D’una banda, el navegador fa una
sol·licitud HTTP. Posteriorment, el servidor la processa i envia, en conseqüència, una resposta HTTP.
Per a entendre millor la seqüència d'esdeveniments que constitueixen una transacció HTTP, anem a veure-
ho amb un exemple.
Suposem que l'usuari escriu l'URL següent al navegador, http://www.example.com/status.php
El navegador interpreta esta URL i genera la següent sol·licitud HTTP, que és enviada al servidor:
Quan un servidor web rep una sol·licitud com aquesta, busca la informació que està representada per
/status.php. Si la informació realment existeix al servidor, la retorna al client (navegador) de la següent
manera, resposta HTTP:
Segons l'estandar HTTP el cliente web pot sol·licitar diverses operacions del servidor, anomenades métodes
HTTP:
2
GET, Obtenir informació del servidor. Aquesta operació s'executa cada vegada que es prem sobre un enllaç
per accedir a una pàgina web. (Sol·licitar un recurs del servidor)
POST, Enviar informació des del client al servidor web. Per exemple, les dades introduïdes en un formulari
web.
HEAD, Similar a GET, però soles es demana la capçalera de la pàgina, amb informació com la grandària, el
tipus, la data de modificació, etc. (Sol·licitar informació sobre un recurs)
…
Pel que fa als codis de resposta, codis d'estat que el servidor envia indicant el resultat de la petició, aquests
són els codis que, habitualment, es veuen quan el navegador no pot mostrar la pàgina web sol·licitada. La
sintaxi d'una resposta HTTP és una línia d'estat que té una estructura fixa on s'indica la versió del protocol,
el codi de l'error i un text explicatiu.
Els possibles codis d'estat s'identifiquen amb números de tres xifres i es classifiquen en cinc grups:
1xx Informational responses, codis informatius.
2xx Succesful responses, codis d'èxit en la sol·licitud.
3xx Redirection messages, codis per tornar a adreçar la sol·licitud.
4xx Client error responses, codis per un error generat en el client.
5xx Server error responses, codis per errors generats en el servidor.
Les respostes més típiques són els codis '200 OK', per indicar la confirmació de la petició, i el '404 Not
Found. The server has not found anything matching the Request-URI', per indicar que l'objecte sol·licitat no
es troba disponible.
5. Installation and configuration of Apache2
Apache is the most commonly used Web server on Linux systems.
Apache Web Servers are often used in combination with the MySQL database engine, the
HyperText Preprocessor (PHP) scripting language, and other popular scripting languages
such as Python and Perl. This configuration is termed LAMP (Linux, Apache, MySQL and
Perl/Python/PHP) and forms a powerful and robust platform for the development and
deployment of Web-based applications.
After its installation, Apache2 is configured by placing directives in plain text configuration
files. These directives are separated between the following files and directories:
• apache2.conf: the main Apache2 configuration file. Contains settings that are
global to Apache2.
• ports.conf: file that houses the directives that determine which TCP ports Apache2
is listening on.
• envvars: file where Apache2 environment variables are set.
• magic: instructions for determining MIME type based on the first few bytes of a file.
• conf-available: this directory contains available configuration files.
• conf-enabled: holds symlinks to the files in /etc/apache2/conf-available. When a
configuration file is symlinked, it will be enabled the next time apache2 is restarted.
• mods-available: this directory contains configuration files to both load modules and
configure them.
• mods-enabled: holds symlinks to the files in /etc/apache2/mods-available. When a
module configuration file is symlinked it will be enabled the next time apache2 is
restarted.
3
• sites-available: this directory has configuration files for Apache2 Virtual Hosts.
Virtual Hosts allow Apache2 to be configured for multiple sites that have separate
configurations.
• sites-enabled: contains symlinks to the /etc/apache2/sites-available directory.
When a configuration file in sites-available is symlinked, the site configured by it will
be active once Apache2 is restarted.
Apache2 is configured with a single default virtual host which can be modified or used as-
is if you have a single site, or used as a template for additional virtual hosts if you have
multiple sites.
To modify the default virtual host, edit the file /etc/apache2/sites-available/000-default.conf.
Or, if you wish to configure a new virtual host or site, copy that file into the same directory
with a name you choose.
Edit the new file to configure the new site using some of the directives described below:
• The VirtualHost directive allows you to configure more than one website on the
same server.
• The ServerAdmin directive specifies the email address to be advertised for the
server's administrator.
• The Listen directive specifies the port, and optionally the IP address, Apache2
should listen on. If the IP address is not specified, Apache2 will listen on all IP
addresses assigned to the machine it runs on. The default value for the Listen
directive is 80.
• The ServerName directive is optional and specifies what FQDN your site should
answer to.
You may also want your site to respond with the www prefix. Use the ServerAlias
directive for this. For example, the following configuration will cause your site to
respond to any domain request ending in .example.com: ServerAlias *.example.com
• The DocumentRoot directive specifies where Apache2 should look for the files that
make up the site. The default value is /var/www/html.
Finally, enable the new VirtualHost using the a2ensite utility and restart Apache2. Similarly,
use the a2dissite utility to disable sites.
Apache és el servidor web més utilitzat en sistemes Linux.
Els servidors web Apache s'utilitzen sovint en combinació amb el motor de bases de dades MySQL, el
llenguatge de script PHP i altres llenguatges de script populars com Python i Perl. Aquesta configuració
s'anomena LAMP (Linux, Apache, MySQL i Perl/Python/PHP) i forma una plataforma potent i robusta per al
desenvolupament i desplegament d'aplicacions basades en web.
Després de la seva instal·lació, Apache2 es configura col·locant directives en fitxers de configuració de text
pla. Aquestes directives estan separades entre els fitxers i directoris següents:
• apache2.conf: el fitxer de configuració principal d'Apache2. Conté paràmetres globals per a Apache2.
• ports.conf: fitxer que allotja les directives que determinen quins ports TCP escolta Apache2.
• envvars: fitxer on s'estableixen les variables d'entorn d'Apache2.
• magic: instruccions per determinar el tipus MIME en funció dels primers bytes d'un fitxer.
4
• conf-available: aquest directori conté fitxers de configuració disponibles.
• conf-enabled: conté enllaços simbòlics als fitxers a /etc/apache2/conf-available. Quan es crea un enllaç a
un fitxer de configuració, s'habilitarà la propera vegada que es reinicie apache2.
• mods-available: aquest directori conté fitxers de configuració tant per carregar mòduls com per configurar-
los.
• mods-enabled: conté enllaços simbòlics als fitxers a /etc/apache2/mods-available. Quan es crea un enllaç
a un fitxer de configuració de mòduls, s'habilitarà la propera vegada que es reinicie apache2.
• sites-available: aquest directori té fitxers de configuració per a hosts virtuals Apache2. Els hosts virtuals
permeten configurar Apache2 per a diversos llocs, que tenen configuracions separades.
• sites-enabled: conté enllaços simbòlics al directori /etc/apache2/sites-available. Quan un fitxer de
configuració a sites-available està enllaçat simbòlicament, el lloc configurat per ell estarà actiu una vegada
es reinicie Apache2.
Apache2 ve configurat amb un únic host virtual predeterminat que es pot modificar o utilitzar tal com és si
teniu un sol lloc, o s'utilitza com a plantilla per a crear hosts virtuals addicionals si teniu diversos llocs.
Per modificar el host virtual predeterminat, editeu el fitxer /etc/apache2/sites-available/000-default.conf. O, si
voleu configurar un nou host o lloc virtual, copieu aquest fitxer al mateix directori amb el nom que trieu.
Editeu el fitxer nou per configurar el nou lloc utilitzant algunes de les directives que es descriuen a
continuació:
• La directiva VirtualHost permet configurar més d'un lloc web al mateix servidor.
• La directiva ServerAdmin especifica l'adreça de correu electrònic que s'ha d'anunciar per a l'administrador
del servidor.
• La directiva Listen especifica el port i, opcionalment, l'adreça IP que Apache2 hauria d'escoltar. Si no
s'especifica l'adreça IP, Apache2 escoltarà per totes les adreces IP assignades a la màquina on s'executa.
El valor per defecte de la directiva Listen és 80.
• La directiva ServerName és opcional i especifica a quin FQDN hauria de respondre el vostre lloc.
També és possible que vulgueu que el vostre lloc respongui amb el prefix www. Utilitzeu la directiva
ServerAlias per a això. Per exemple, la configuració següent farà que el vostre lloc responga a qualsevol
sol·licitud de domini que acabe en .example.com: ServerAlias *.example.com
• La directiva DocumentRoot especifica on Apache2 ha de buscar els fitxers que formen el lloc. El valor per
defecte és /var/www/html.
Finalment, habiliteu el nou VirtualHost mitjançant la utilitat a2ensite i reinicieu Apache2. De la mateixa
manera, utilitzeu la utilitat a2dissite per desactivar els llocs.
6. Virtual servers
When we talk about creating virtual sites we are referring to the action of running more
than one web site, for example the example1.cat and example2.cat web pages, on a
single computer server. Even if both domains are running on the same physical machine,
we will never realize this when we visit these websites.
To explain the technique of creating virtual web sites we will work with the previous
example.
The two virtual web sites will be served by the same web server. The default directory
where the web pages are located is /var/www, where we will create the different directory
structures. So, inside the directories /var/www/example1.cat and /var/www/example2.cat
we will find the files of the web sites corresponding to the previous web pages.
Once we have defined the directories where we will store the virtual web sites, we will go
to the directory /etc/apache2/sites-available. In this directory we will create the
configuration files for each virtual site: example1.com.conf and example2.com.conf.
5
At this point, we will have to consider which virtual web site configuration we want to
create:
• Virtual sites based on the IP address. In this case, we will be able to host multiple
domains on a single machine that will have different IP addresses and, on each of
them, a virtual site will be executed.
• Virtual sites based on the domain name. The problem with virtual websites based
on IP addresses is that, considering that many domains are hosted, we will need an
IP address for each of the domains. Therefore, it may be preferable to work with
virtual sites based on domain names.
In this case, several websites with different domain names will be working with a
single IP address, that of the web server.
In the case of working with a DNS server, it must be configured to resolve these
sites in the corresponding zones. (In the case of not having a DNS server, we will
have to configure the /etc/hosts file of each client computer)
• Virtual sites based on the port. In this case, we will be able to host multiple
domains on a single machine that will listen on multiple ports. In each of them, a
virtual site will run.
Quan parlem de la creació de llocs virtuals ens estem referint a l’acció de fer treballar més d’un lloc web, per
exemple les pàgines web example1.cat i example2.cat, en un únic ordinador servidor. Encara que els dos
dominis estiguen treballant en la mateixa màquina física, mai ens n’adonarem quan visitem aquests llocs
web.
Per explicar la tècnica de la creació de llocs web virtuals treballarem amb l'exemple anterior.
Els dos llocs webs virtuals seran servits pel mateix servidor web. El directori per defecte on es troben les
pàgines web és /var/www, on crearem les diferents estructures de directori. Per tant, dins dels directoris
/var/www/example1.cat i /var/www/example2.cat trobarem els arxius dels llocs web corresponents a les
pàgines web anteriors.
Una vegada definits els directoris on desarem els llocs web virtuals, haurem d’adreçar-nos al directori
/etc/apache2/sites-available. Dins d'aquest directori crearem els fitxers de configuració de cada lloc virtual:
example1.com.conf i example2.com.conf
Una vegada ací haurem de considerar quina configuració de lloc web virtual volem crear:
- Llocs virtuals basats en l'adreça IP. En aquest cas, podrem allotjar múltiples dominis en una única màquina
que disposarà de diferents adreces d’Internet (IP) i, en cadascuna d’elles, s’hi executarà un lloc virtual.
- Llocs virtuals basats en el nom de domini. El problema dels llocs web virtuals basats en adreces IP és que,
considerant que s'allotgen molts dominis, necessitarem una adreça IP per a cadascun dels dominis. Per
tant, pot ser preferible treballar amb llocs virtuals basats en noms de domini.
En aquest cas, diversos llocs web amb diferents noms de domini estaran treballant amb una única adreça
IP, la del servidor web.
En el cas de treballar amb servidor DNS, aquest haurà d'estar configurat per resoldre aquests llocs en les
zones corresponents. (En el cas de no tenir un servidor DNS, haurem de configurar el fitxer /etc/hosts de
cada ordinador client)
- Llocs virtuals basats en el port. En aquest cas, podrem allotjar múltiples dominis en una única màquina
que escoltarà en diversos ports. En cadascun d'ells, s'hi executarà un lloc virtual.
7. Anonymous and authenticated access
Web servers can be configured to provide different authentication models, which allow
controlling access to a given browsing space.
6
If you want to offer a public site that any user is able to access, you will need to allow
anonymous access, so that no credentials are required.
If, on the contrary, it is required that only certain users be able to access a site, it will be
necessary to apply an authenticated access control. It will determine whether or not to
grant access to a resource based on the credentials the client provides.
Els servidors web es poden configurar per proporcionar diferents models d'autenticació, que permeten
controlar l'accés que es fa sobre un espai de navegació determinat.
Si voleu oferir un lloc públic al qual qualsevol usuari sigua capaç d'accedir-hi, cal permetre l'accés anònim,
de manera que no se sol·licite cap credecial.
Si, per contra, cal que només determinats usuaris siguen capaços d'accedir a un lloc, caldrà aplicar un
control d'accés autenticat. Aquest determinarà si s'ofereix accés o no a un recurs en funció de les
credencials que el client proporcione.
8. Code execution. Server and client scripts
9. Establishing secure connections
A secure website is a site that uses the HTTPS protocol (port 443 over TCP) instead of the
HTTP protocol. In fact, the HTTPS protocol is identical to the HTTP protocol with the
exception that the transfer of information between the client (web browser) and the web
server travels encrypted over the network.
The encryption algorithms used, provided by SSL/TLS encryption protocols, have the
necessary characteristics to ensure that the information that goes out from the server to
7
the client is encrypted and can only be decrypted by the client, and that the information
that goes out from the client to the server is encrypted and can only be decrypted by the
server. In addition, the server presents the site's digital certificate that authenticates it as a
genuine and trusted provider.
During transmission, symmetric encryption algorithms will be used, but for the purpose of
exchanging the encryption key, there is an initial asymmetric encryption session. (Hybrid
cryptography)
The mod_ssl module adds the ability to encrypt communications to the Apache2 server. To
enable it we will run the command: a2enmod ssl. The default HTTPS configuration file is
/etc/apache2/sites-available/default-ssl.conf.
Un lloc web segur és un lloc que utilitza el protocol HTTPS (port 443 sobre TCP) en lloc del protocol HTTP.
De fet, el protocol HTTPS és idèntic al protocol HTTP amb l’excepció que la transferència d’informació entre
el client (navegador web) i el servidor web viatja xifrada per la xarxa.
Els algoritmes de xifrat utilitzats, proporcionats pels protocols de xifrat SSL/TLS, reuneixen les
característiques necessàries per garantir que la informació que surt del servidor cap al client estiga xifrada i
que només puga ser desxifrada pel client, i que la informació que surt del client cap al servidor estiga xifrada
i només puga ser desxifrada pel servidor. A més, el servidor presenta el certificat digital del lloc que
l'autentica com un proveïdor genuí i de confiança.
Durant la transmissió, s'utilitzaran algoritmes de xifrat simètrics, però, amb la finalitat d’intercanviar la clau
de xifrat, hi ha una sessió inicial de xifrat asimètric. (Criptografia híbrida)
El mòdul mod_ssl afegeix l'habilitat d'encriptar les comunicacions al servidor Apache2. Per a habilitar-lo
executarem el comandament: a2enmod ssl. El fitxer de configuració HTTPS predeterminat és /etc/apache2/
sites-available/default-ssl.conf.