Web server

From Sinfronteras
Jump to: navigation, search

In computing, a server is a computer program or a device that provides functionality for other programs or devices, called clients. Typical servers are database servers, file servers, mail servers, print servers, web servers, game servers, and application servers.

The computer that a server program runs in is also frequently referred to as a server (Server machine).

A web server is a computer system that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web. https://en.wikipedia.org/wiki/Web_server

How do web pages get served to our browser?

A web server is a computer system that processes requests via HTTP protocol.

A web server delivers the files (or resource) that the user is looking for.

  • HTTP protocol (Hypertext Transfer Protocol). Think of protocols as a standard way of communicating between a client and a server in an agreed way.
    • HTTP is a stateless asynchronous request-response application-layer protocol.
    • A client sends a request message to the server. The server then returns a response message to the client. In other words, HTTP is a pull protocol, a client pulls a page from the server.
    • HTTP Request:
      • Step 1: Web address entered by a user is translated into an I.P address using a Domain Name Server (DNS)
      • Step 2: The I.P address of the website we are looking for is given to us and then the web browser makes a connection to the web server at the location specified by the address and asks for the page we are requesting.
      • Step 3: The web server looks for the page we are requesting and then sends it back to the user after executing any server side code e.g. PHP within the file (response).
HTTP request1.png
HTTP request2.png
  • Other protocols:
    • FTP - File Transfer Protocol , transferring files from client to server
    • SMPT - Simple Mail Transfer Protocol, Internet standard for email transmission
    • HTTPS - similar to HTTP but is more secure. It allows for the transfer of encrypted data over the internet to avoid “packet sniffing”

  • Web servers generally work on port 80:
Different services work on different ports. The 80 one is generally used for web servers. A port number is used to identify a specific process to which an internet or other network message is to be forwarded when it arrives at a server.
When we specify an address (www.example.com) port 80 is assumed. We could also enter www.example.com:80
Sometimes we need to run multiple web servers on our development machines so sometime we may start a web server on a port other than 80. If so we need to specify the port of the web server process we require: www.localhost:8080 where 8080 is the port we started the web server process on.

  • Document Root: How does a web server know where to find the files (or resources ) we require?
The web server has access to a directory where all of the files that can be served to a user via a request are located (Document Root). Typically called htdocs or www.

  • Server HTTP Status Codes:
When we are working with a web server, the HTTP protocol has a number of standard codes which the server returns as part of the response to the client who has issued a request.
  • Code we want to see is code 200 which indicates everything is ok
  • One codes we want to avoid is the 404 code, which means that the requested page cannot be found.
  • These are the most common codes, but there are many more. We can interrogate the response code and take appropriate action e.g. error messages of dreaded 404 web page
In general response codes can be classified as:
  • 1xx (Informational): The request was received, continuing process
  • 2xx (Successful): The request was successfully received, understood, and accepted
  • 3xx (Redirection): Further action needs to be taken in order to complete the request
  • 4xx (Client Error): The request contains bad syntax or cannot be fulfilled
  • 5xx (Server Error): The server failed to fulfill an apparently valid request

  • The web server we pick depends on the technology we are developing (PHP, ASP.NET or others) and the your operating system.
In general we begin building an application, choosing the software we want to develop in first (PHP/MySQL) and develop locally on our development machines. When the time comes to move the Web pages to production then we need to make the decisions about where and how our application will run based on our needs as to the operating system and web server requirements.
A web server should always be running (high availability). This is important when choosing a web hosting provider. Look for their availability statistics before entering into an agreement.
How to Choose de host: Linux, windows etc... se habla un poco de esto en las láminas de 1-Lecture 1_intro_web_development.pdf, no parece muy importante.

Web server solution stack package

Estos Stack package permiten instalar y configurar de una forma compacta, los programas necesarios para Desarrollo Web. Por supuesto, también podemos instalar y configurar los programas por separado (A Web server: Apache ; Serveur de base de données: MySql (mysql-server) ; PHP)





XAMPP is a free and open source cross-platform (Windows, Linux, MacOS) server solution stack package developed by Apache Friends. Consisting mainly of:

  • X as an ideographic letter referring to cross‑platform: Windows, Linux, MacOS
  • A Apache or its expanded form, Apache HTTP Server
  • M MariaDB (formerly: MySQL)
  • P PHP
  • P Perl

Once the sever is running we need to put all our Web pages in the folder location specified by Document Root. Normally will be:


LAMP Stack


A LAMP (Linux, Apache, MySQL, PHP) stack is a common, free and open-source web stack used for hosting web content in a Linux environment.

Quick Install Using Tasksel

Instead of installing Apache, MySQL, and PHP separately, tasksel offers a convenient way to get a LAMP stack running quickly.

Install tasksel if not already installed by default.

sudo apt install tasksel

Use tasksel to install the LAMP stack.

sudo tasksel install lamp-server

Enter the prompt for a MySQL root password. See the steps below for Apache configurations, creating a virtual host, and installation of PHP modules for Wordpress installation.


The Apache HTTP Server, colloquially called Apache, is the world's most used web server software.

Apache config files: En XAMPP las configuraciones se hacen generalmente en el archivo:


En Ubuntu hay varios archivos en el directorio /etc/apache2 que permiten realizar configuraciones. Algunos son:

/etc/apache2/sites-available/000-default.conf    (Aquí se configura el DocumentRoot)
/etc/apache2/ports.conf                          (Aquí se configura el puerto)

En dichos archivo se configura, entre otras cosas:

Document Roo: Under the /var/www/html ("C:/xampp/htdocs" en XAMP) folder we place our folders and files we want Apache web server to serve up to us on request

DocumentRoot   /var/www/html

Port setting (change here if want to start Apache on different port):

Listen 80:  

The Http address (localhost) se configura en la siguiente línea:

ServerName localhost:80:

Installing Apache


Apache Web Server (Apache HTTP Server): https://en.wikipedia.org/wiki/Apache_HTTP_Server

Instalar la última versión incluida por defecto en los repositorios de Ubuntu:

sudo apt update
sudo apt install apache2

Para instalar la última versión (2.4.34): https://websiteforstudents.com/install-the-latest-apache2-2-4-34-on-ubuntu-16-04-17-10-18-04-lts-servers/

sudo add-apt-repository ppa:ondrej/apache2
sudo apt update
sudo apt install apache2

La instalación la última versión (si ésta es muy reciente) puede generar errores que no habn sido aún corregidos y documentados por la comunidad. Recomiendo instalar la última versión incluida por defecto en los repositorios de Ubuntu

Vous pouvez faire un contrôle sur place pour vérifier que tout s'est déroulé comme prévu en visitant l'adresse IP publique de votre serveur dans votre navigateur Web: https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04


Si tout s'est bien passé, vous verrez la page web d'Apache qui est configurée par défaut dans votre système.

Apache User-Group Name and ID

En esta página se muestran varios métodos para obtener el User and Group of Apache: https://www.cyberciti.biz/faq/unix-osx-linux-find-apache-user/

apachectl -S
ps aux | egrep '([a|A]pache|[h|H]ttpd)'
ps aux | egrep '([a|A]pache|[h|H]ttpd)' | awk '{ print $1}' | uniq | tail -1
ps -ef | egrep '(httpd|apache2|apache)' | grep -v `whoami` | grep -v root | head -n1 | awk '{print $1}'

Para desplegar el Apache user-id (UID) and groupd-id: http://www.digimantra.com/linux/find-users-uid-gid-linux-unix/

id -u www-data
id -g www-data

El comando id despliega el id de cualquier usuario o grupo (no sólo del Apache user).

Start-Stop-Restart Apache Service

sudo service apache2 start
sudo service apache2 stop
sudo service apache2 restart

How do I change the root directory of an apache server



Please note, that this only applies for Ubuntu 14.04 LTS and newer releases.

In my Ubuntu 14.04 LTS, the document root was set to /var/www/html. It was configured in the following file:


So just do a

sudo nano /etc/apache2/sites-available/000-default.conf

and change the following line to what you want:

DocumentRoot /var/www/html

Also do a

sudo nano /etc/apache2/apache2.conf

and find this

<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted

and change /var/www/html to your preferred directory

and save it.

After you saved your changes, just restart the apache2 webserver and you'll be done :)

Change Apache HTTP default Port


sudo vi /etc/apache2/ports.conf     [On Debian/Ubuntu]
sudo vi /etc/httpd/conf/httpd.conf  [On RHEL/CentOS]

PHP version used by apache

Al actualizar la versión de PHP (o si tenemos varias versiones de PHP instaladas) puede ser necesario configurar la versión de PHP que queremos que Apache use. La cuestión es que la versión de PHP que se muestra al ejecutar «php --version» puede ser distinta a la que está usando Apache. https://superuser.com/questions/969861/phpinfo-and-php-v-shows-different-version-of-php/1083828

Para saber cuales son las versiones de PHP disponibles: https://superuser.com/questions/969861/phpinfo-and-php-v-shows-different-version-of-php/1083828

ls /etc/apache2/mods-available/php*.load

Ahora, para configurar la versión de PHP que Apache utilizará: https://tecadmin.net/switch-between-multiple-php-version-on-ubuntu/

Primero desactivamos la que está usando actualmente:

sudo a2dismod php5.6

Para luego activar la que queremos:

sudo a2enmod php7.2

Por último:

sudo service apache2 restart

Add a subdomain



  • Create a .config file. Go to «/etc/apache2/sites-available» and create a file:


<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/sinfronteras/wikis/wiki
    ServerAlias   www.wiki.sinfronteras.ws
    ServerName wiki.sinfronteras.ws

    <Directory /var/www/sinfronteras/wikis/wiki>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        allow from all
                Require all granted

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

  • Create the directory for your site in /var/www/sinfronteras/wikis/wiki (or wherever you said it was in the config file)

  • Enable the site in apache with:
sudo a2ensite wiki_sinfronteras_ws.conf (or whatever you named your .conf file)

  • Reload apache:
sudo service apache2 reload

  • Make sure the <VirtualHost *:80> port match the «Listen 80» port configured in the «/etc/apache2/ports.conf» file


Install NGINX on Unbuntu/Debian

sudo apt-get install nginx

Es impotante notar que, if there is already a process running in port 80 (An Apache Web server running for example) al final de la instalación de «nginx», cuando el programa de instalación intente iniciar el servicio «nginx» se desplegará un error indicando que el servicio no se pudo iniciar. Esto se debe a que el puerto 80 (puerto utilizado por nginx por defecto) ya está siendo utilizado. Para solucionar este problema podemos:

sudo fuser -k 80/tcp

and then restart NGINX

Luego de esto podemos iniciar nginx:

sudo systemctl start nginx.service

Start/Stop/Restart NGINX service

sudo systemctl start   nginx.service
sudo systemctl stop    nginx.service
sudo systemctl restart nginx.service

Change NGINX HTTP default Port


sudo vi /etc/nginx/sites-available/default
 server {
        listen 8082 default_server;
        listen [::]:8082 default_server;

504 Gateway Timeout error


This problem was solved by adding the file:

/etc/nginx/conf.d/timeout.conf :
proxy_connect_timeout       600;
proxy_send_timeout          600;
proxy_read_timeout          600;
send_timeout                600;

Then, restart nginx service.

Usar dos Web server (por ejemplo Apache y NGINX) en la misma computadora

Para poder ingresar a distintos Web servers instalados en la misma computadora, lo único que hay que hacer es configurar puertos distintos para cada servidor. Ver: Web server#Change Apache HTTP default Port

Web server#Change NGINX HTTP default Port

Podría también ser necesario, configurar los Firewalls para poder acceder a otros puertos.

Hide Pages, Files, and Directories from Search Engines as Google - The Robots.txt file


En MediaWiki - Robots.txt


Block an IP from your site using htaccess

Block a country from your site using htaccess


De esta forma lo logré hacer:

Este método plantea obtener la lista de IP's a bloquear from here: https://www.ip2location.com/free/visitor-blocker y colocarla en el archivo .htaccess. Éste archivo se coloca en cualquier directorio y afectará todos los subdirectorios. En mi caso lo he colocado en el directorio principal de MediaWiki (/var/www/sinfronteras_ws/perso) para que afecte todas las páginas del MediaWiki

Sin embargo,

Aquí se muestran varias formas de hacerlo: https://www.sitepoint.com/how-to-block-entire-countries-from-accessing-website/

Parece que el método más apropiado es a través es este:

Apache Modules

You don’t have to fill your .htaccess file with thousands of lines of IPs. Instead, you can install a C library and an Apache module to do the heavy lifting for you.

MaxMind provides a popular free database that is often used for IP lookups. Their GeoLite2 is a free database that is updated monthly. Their paid product is more accurate and updated more frequently if you require that.

By using this database and installing one of their various APIs, you can handle traffic as you see fit.

For our purposes, you would need to install the C library API as well as the Apache module. Once those are working and enabled, place the database file somewhere, and then you can set up your country blocks with code as simple as this in the .htaccess or Apache config file...

Explicación de los archivos .htaccess, donde colocarlo y cómo se activa en Apache: