Premiers Pas

Installation sur systèmes Debian

A ce stade, nous donnerons une courte et simple procédure d’installation pour une configuration de travail minimale sur système Debian . De nombreuses autres distributions et OS proposent aussi des paquets pour QGIS Server.

La configuration et les étapes pour installer QGIS Server sur un système basé sur Debian sont fournies dans la page installateurs QGIS. Veuillez vous référer à cette page.

Configuration d’un serveur HTTP

Apache

Apache and its mod_fcgid module may be used for executing QGIS Server.

Install Apache and mod_fcgid:

sudo apt install apache2 libapache2-mod-fcgid

Here we assume that an Apache VirtualHost is already set up. For example this is what a basic VirtualHost configuration may look like:

<VirtualHost *:80>

 ServerAdmin [email protected]
 DocumentRoot /var/www/html

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

</VirtualHost>

Note

On Debian systems, a default VirtualHost is available in /etc/apache2/sites-available/000-default.conf.

Let’s now add mod_fcgid configuration directives for QGIS Server:

<VirtualHost *:80>

 ServerAdmin [email protected]
 DocumentRoot /var/www/html

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

 FcgidInitialEnv DISPLAY ":99"
 FcgidInitialEnv QGIS_SERVER_LOG_LEVEL "0"
 FcgidInitialEnv QGIS_SERVER_LOG_STDERR "1"

 <Location /qgisserver>
  SetHandler fcgid-script
  FcgidWrapper /usr/lib/cgi-bin/qgis_mapserv.fcgi virtual
  Options +ExecCGI -MultiViews +FollowSymLinks
  Require all granted
 </Location>

</VirtualHost>

See the mod_fcgid documentation for more information on the Fcgid parameters used. And see below to understand when and why the DISPLAY environment variable needs to be set.

Now restart Apache for the new configuration to be taken into account:

sudo service apache2 restart

QGIS Server est maintenant disponible sur http://localhost/qgisserver.

NGINX

Vous pouvez également utiliser QGIS Server avec NGINX. Contrairement à Apache, NGINX ne génère pas automatiquement des processus FastCGI. Les processus FastCGI doivent être démarrés autrement.

Sur les systèmes basés sur Debian, vous pouvez utiliser fcgiwrap ou spawn-fcgi pour démarrer et gérer les processus QGIS Server. Les paquets Debian officiels existent pour les deux.

Note

fcgiwrap est plus facile à configurer que spawn-fcgi, car il est déjà intégré dans un service Systemd. Mais cela conduit aussi à une solution beaucoup plus lente que l’utilisation de spawn-fcgi. Avec fcgiwrap, un nouveau processus QGIS Server est créé à chaque requête, ce qui signifie que le processus d’initialisation de QGIS Server, qui inclut la lecture et l’analyse du fichier projet QGIS, est effectué sur chaque requête. Avec spawn-fcgi, le processus QGIS Server est conservé entre les requêtes, ce qui se traduit par de bien meilleures performances. Pour cette raison, le spawn-fcgi est recommandé pour une utilisation en production.

Install NGINX:

sudo apt install nginx
fcgiwrap

Si vous voulez utiliser fcgiwrap pour exécuter QGIS Server, vous devez d’abord installer le paquet correspondant :

sudo apt install fcgiwrap

Ensuite, introduisez le bloc suivant dans votre configuration de serveur NGINX :

1
2
3
4
5
6
  location /qgisserver {
      gzip           off;
      include        fastcgi_params;
      fastcgi_pass   unix:/var/run/fcgiwrap.socket;
      fastcgi_param  SCRIPT_FILENAME /usr/lib/cgi-bin/qgis_mapserv.fcgi;
  }

Enfin, redémarrez NGINX et fcgiwrap pour prendre en compte la nouvelle configuration :

sudo service nginx restart
sudo service fcgiwrap restart

QGIS Server est maintenant disponible sur http://localhost/qgisserver.

spawn-fcgi

Si vous préférez utiliser spawn-fcgi au lieu de fcgiwrap, la première étape consiste à installer le paquet :

sudo apt install spawn-fcgi

Ensuite, introduisez le bloc suivant dans votre configuration de serveur NGINX :

location /qgisserver {
    gzip           off;
    include        fastcgi_params;
    fastcgi_pass   unix:/var/run/qgisserver.socket;
}

Et redémarrez NGINX pour prendre en compte la nouvelle configuration :

sudo service nginx restart

Enfin, étant donné qu’il n’y a pas de fichier de service par défaut pour spawn-fcgi, vous devez démarrer manuellement QGIS Server dans votre terminal :

sudo spawn-fcgi -s /var/run/qgisserver.socket \
                -U www-data -G www-data -n \
                /usr/lib/bin/cgi-bin/qgis_mapserv.fcgi

Bien sûr, vous pouvez écrire un script d’initialisation (comme un fichier ``qgisserver.service``avec Systemd) pour lancer QGIS Server au démarrage ou quand vous voulez.

QGIS Server est maintenant disponible sur http://localhost/qgisserver.

Note

Avec la commande ci-dessus, spawn-fcgi ne génère qu’un seul processus QGIS Server. Pour utiliser plus d’un processus QGIS Server, vous pouvez combiner spawn-fcgi avec l’outil multiwatch, qui est également empaqueté dans Debian.

Configuration

La ligne include fastcgi_params; utilisée dans la configuration précédente est importante car elle ajoute les paramètres de /etc/nginx/fastcgi_params :

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

Vous pouvez bien sûr, remplacer ces variables dans votre propre configuration. Par exemple :

include fastcgi_params;
fastcgi_param SERVER_NAME domain.name.eu;

De plus, vous pouvez utiliser certains Variables d’environnement pour configurer QGIS Server. Avec NGINX comme serveur HTTP, vous devez utiliser fastcgi_param pour définir ces variables comme indiqué ci-dessous :

fastcgi_param  QGIS_DEBUG              1;
fastcgi_param  QGIS_SERVER_LOG_FILE    /tmp/qgis-000.log;
fastcgi_param  QGIS_SERVER_LOG_LEVEL   0;

Note

Lors de l’utilisation de spawn-fcgi, vous pouvez définir directement les variables d’environnement avant d’exécuter le serveur. Par exemple : `exporter QGIS_SERVER_LOG_LOG_FILE=/home/user/qgis.log`.

Xvfb

QGIS Server needs a running X Server to be fully usable. But if you don’t have one, you may use xvfb to have a virtual X environment.

To install the package:

sudo apt install xvfb

Then, according to your HTTP server, you should configure the DISPLAY parameter or directly use xvfb-run.

For example with NGINX and spawn-fcgi using xvfb-run:

xvfb-run /usr/bin/spawn-fcgi -f /usr/lib/bin/cgi-bin/qgis_mapserv.fcgi \
                             -s /tmp/qgisserver.socket \
                             -G www-data -U www-data -n

The other option is to start a virtual X server environment with a specific display number thanks to Xvfb:

/usr/bin/Xvfb :99 -screen 0 1024x768x24 -ac +extension GLX +render -noreset

Then we just have to set the DISPLAY environment variable in the HTTP server configuration. For example with NGINX:

fastcgi_param  DISPLAY       ":99";

Or with Apache:

FcgidInitialEnv DISPLAY       ":99"

Installation on Windows

QGIS Server can also be installed on Windows systems. While the QGIS Server package is available in the 64 bit version of the OSGeo4W network installer (https://qgis.org/en/site/forusers/download.html) there is no Apache (or other web server) package available, so this must be installed by other means.

A simple procedure is the following:

../../../../_images/qgis_server_windows1.png
  • Download the OSGeo4W installer, follow the « Advanced Install » and install both the QGIS Desktop and QGIS Server packages

../../../../_images/qgis_server_windows2.png
  • Edit the httpd.conf file (C:\xampp\apache\httpd.conf if the default installation paths have been used) and make the following changes:

From:

ScriptAlias /cgi-bin/ "C:/xampp/cgi-bin/"

To:

ScriptAlias /cgi-bin/ "c:/OSGeo4W64/apps/qgis/bin/"

From:

<Directory "C:/xampp/cgi-bin">
AllowOverride None
Options None
Require all granted
</Directory>

To:

<Directory "c:/OSGeo4W64/apps/qgis/bin">
SetHandler cgi-script
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
Require all granted
</Directory>

From:

AddHandler cgi-script .cgi .pl .asp

To:

AddHandler cgi-script .cgi .pl .asp .exe

Then at the bottom of httpd.conf add:

SetEnv GDAL_DATA "C:\OSGeo4W64\share\gdal"
SetEnv QGIS_AUTH_DB_DIR_PATH "C:\OSGeo4W64\apps\qgis\resources"
SetEnv PYTHONHOME "C:\OSGeo4W64\apps\Python36"
SetEnv PATH "C:\OSGeo4W64\bin;C:\OSGeo4W64\apps\qgis\bin;C:\OSGeo4W64\apps\Qt5\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem"
SetEnv QGIS_PREFIX_PATH "C:\OSGeo4W64\apps\qgis"
SetEnv QT_PLUGIN_PATH "C:\OSGeo4W64\apps\qgis\qtplugins;C:\OSGeo4W64\apps\Qt5\plugins"

Restart the Apache web server from the XAMPP Control Panel and open browser window to testing a GetCapabilities request to QGIS Server

http://localhost/cgi-bin/qgis_mapserv.fcgi.exe?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetCapabilities

Serve a project

Now that QGIS Server is installed and running, we just have to use it.

Obviously, we need a QGIS project to work on. Of course, you can fully customize your project by defining contact information, precise some restrictions on CRS or even exclude some layers. Everything you need to know about that is described later in Configure your project.

But for now, we are going to use a simple project already configured. To retrieve the project:

cd /home/user/
wget https://github.com/qgis/QGIS-Training-Data/archive/QGIS-Training-Data-v2.0.zip -O qgis-server-tutorial.zip
unzip qgis-server-tutorial.zip
mv QGIS-Training-Data-QGIS-Training-Data-v2.0/training_manual_data/qgis-server-tutorial-data ~

The project file is qgis-server-tutorial-data-master/world.qgs. Of course, you can use your favorite GIS software to open this file and take a look on the configuration and available layers.

By opening the project and taking a quick look on layers, we know that 4 layers are currently available:

  • airports

  • places

  • countries

  • countries_shapeburst

You don’t have to understand the full request for now but you may retrieve a map with some of the previous layers thanks to QGIS Server by doing something like this in your web browser to retrieve the countries layer:

http://localhost/qgisserver?
  MAP=/home/user/qgis-server-tutorial-data-master/world.qgs&
  LAYERS=countries&
  SERVICE=WMS&
  REQUEST=GetMap&
  CRS=EPSG:4326&
  WIDTH=400&
  HEIGHT=200

If you obtain the next image, then QGIS Server is running correctly:

../../../../_images/server_basic_getmap.png

Server response to a basic GetMap request

Note that you may define PROJECT_FILE environment variable to use a project by default instead of giving a MAP parameter (see Variables d’environnement).

For example with spawn-fcgi:

export PROJECT_FILE=/home/user/qgis-server-tutorial-data-master/world.qgs
spawn-fcgi -f /usr/lib/bin/cgi-bin/qgis_mapserv.fcgi \
           -s /var/run/qgisserver.socket \
           -U www-data -G www-data -n

Configure your project

To provide a new QGIS Server WMS, WFS or WCS, you have to create a QGIS project file with some data or use one of your current project. Define the colors and styles of the layers in QGIS and the project CRS, if not already defined.

../../../../_images/ows_server_definition.png

Définitions pour un projet WMS/WFS/WCS de QGIS Server

Then, go to the QGIS Server menu of the Project ‣ Properties… dialog and provide some information about the OWS in the fields under Service Capabilities. This will appear in the GetCapabilities response of the WMS, WFS or WCS. If you don’t check checkbox Service capabilities, QGIS Server will use the information given in the wms_metadata.xml file located in the cgi-bin folder.

Capacités WMS

In the WMS capabilities section, you can define the extent advertised in the WMS GetCapabilities response by entering the minimum and maximum X and Y values in the fields under Advertised extent. Clicking Use Current Canvas Extent sets these values to the extent currently displayed in the QGIS map canvas. By checking checkbox CRS restrictions, you can restrict in which coordinate reference systems (CRS) QGIS Server will offer to render maps. It is recommended that you restrict the offered CRS as this reduces the size of the WMS GetCapabilities response. Use the signPlus button below to select those CRSs from the Coordinate Reference System Selector, or click Used to add the CRSs used in the QGIS project to the list.

If you have print layouts defined in your project, they will be listed in the GetProjectSettings response, and they can be used by the GetPrint request to create prints, using one of the print layout layouts as a template. This is a QGIS-specific extension to the WMS 1.3.0 specification. If you want to exclude any print layout from being published by the WMS, check checkbox Exclude layouts and click the signPlus button below. Then, select a print layout from the Select print layout dialog in order to add it to the excluded layouts list.

If you want to exclude any layer or layer group from being published by the WMS, check checkbox Exclude Layers and click the signPlus button below. This opens the Select restricted layers and groups dialog, which allows you to choose the layers and groups that you don’t want to be published. Use the Shift or Ctrl key if you want to select multiple entries. It is recommended that you exclude from publishing the layers that you don’t need as this reduces the size of the WMS GetCapabilities response which leads to faster loading times on the client side.

Vous pouvez recevoir la réponse GetFeatureInfo en texte simple, XML et GML. Le format par défaut est le XML. Le texte simple et le GML dépendent du format de sortie choisi lors de la requête GetFeatureInfo.

If you wish, you can check checkbox Add geometry to feature response. This will include in the GetFeatureInfo response the geometries of the features in a text format.

As many web clients can’t display circular arcs in geometries you have the option to segmentize the geometry before sending it to the client in a GetFeatureInfo response. This allows such clients to still display a feature’s geometry (e.g. for highlighting the feature). You need to check the checkbox Segmentize feature info geometry to activate the option.

You can also use the GetFeatureInfo geometry precision option to set the precision of the GetFeatureInfo geometry. This enables you to save bandwidth when you don’t need the full precision.

If you want QGIS Server to advertise specific request URLs in the WMS GetCapabilities response, enter the corresponding URL in the Advertised URL field.

Furthermore, you can restrict the maximum size of the maps returned by the GetMap request by entering the maximum width and height into the respective fields under Maximums for GetMap request.

Si une de vos couches utilise l’affichage d’indication de carte <maptips>`(pour afficher du texte issu d’expressions), cette dernière sera listée au sein de la sortie GetFeatureInfo. Si la couche utilise une Valeur Relationnelle pour un de ses attributs, cette information sera également renvoyée par la sortie de GetFeatureInfo.

Capacités WFS

Dans la partie Capacités WFS, vous pouvez sélectionner les couches qui vous voulez publier en WFS et indiquer si elle permettent les opérations de mise à jour, d’insertion et de suppression. Si vous ajoutez une URL dans le champ URL publiée des Capacités WFS, QGIS Server annoncera cette URL spécifique dans la réponse WFS GetCapabilities.

Capacités WMS

Dans la partie Capacités WCS, vous pouvez sélectionner les couches qui vous voulez publier en WCS. Si vous indiquez une URL dans le champ URL publiée de la section Capacités WCS, QGIS Server annoncera cette URL spécifique dans la réponse WCS GetCapabilities.

Bien configurer votre OWS

Pour les couches vectorielles, le menu Champs de la fenêtre Couche ‣ Propriétés vous permet de définir quels attributs seront publiés. Par défaut, tous les attributs sont publiés par votre WMS et WFS. Si vous souhaitez ne pas publier un attribut donné, décochez la case correspondante sous la colonne WMS ou WFS.

You can overlay watermarks over the maps produced by your WMS by adding text annotations or SVG annotations to the project file. See the Outils d’annotation section for instructions on creating annotations. For annotations to be displayed as watermarks on the WMS output, the Fixed map position checkbox in the Annotation text dialog must be unchecked. This can be accessed by double clicking the annotation while one of the annotation tools is active. For SVG annotations, you will need either to set the project to save absolute paths (in the General menu of the Project ‣ Properties… dialog) or to manually modify the path to the SVG image so that it represents a valid relative path.