Joseph Zikusooka ~ Zik

A Linux software engineer specializing in open source technologies | Very experienced in building and configuring UNIX/Linux systems and servers. Passionate about developing software applications and hardware for the smart home | Currently serving as the CEO of Jambula Labs and the project leader at JambulaTV, a smart home automation and entertainment platform - https://jambulatv.com | This blog focuses on the following areas: Linux How-Tos and Tutorials ::: IT Security News ::: Free and Libre Open Source Software ::: Smart Home Software ::: Digital Innovations in East Africa https://mastodon.social/@jzik | https://github.com/zikusooka

Author : Joseph Zikusooka

I am a software engineer and developer specializing in open source software. I have a solid experience building and configuring UNIX/Linux systems and servers. I am passionate about developing software applications and hardware for the smart home I am currently serving as the CEO of Jambula Labs and the project leader at JambulaTV, a smart home automation

How to receive Linux server alerts on your phone via WhatsApp

In my last article, I wrote about how to receive Linux server alerts on your phone via telegram. While telegram has a rich feature set, it is still not as popular as whatsapp at least in most regions. Almost, everyone I know is using whatsapp. With the recent addition of end-to-end ecryption, I’ve since relaxed my negative opinions of this service. Therefore, I decided to write a follow-up to my previous article, and show you how to get alerts from your Linux server via whatsapp. I will not delve into the setup of icinga2, however, once you are able to send messages to whatsapp, things should be pretty much self explanatory.

Thanks to Tarek Galal, who wrote a python library called yowsup to interface with whatsapp API.

First install it as follows:

pip install yowsup2

If installation fails, ensure that your have installed all the required dependencies on your Linux box which include python2.6+, python-dateutil, argparse,readline, pillow. If you intend to use encryption, you will need to install protobuf, pycrypto, python-axolotl-curve25519

Yowsup comes with a command-line tool appropriately named; yowsup-cli. For a full understanding of its usage, please visit the yowsup-cli wiki

Registration

As expected, you will need to register your phone. This can be done simply as follows:

yowsup-cli registration -d -E android -m 641 -n 10 -p 256XXXXXXXXX -C 256 -r sms

The arguments explained:
-d For debugging
-E This is the environment. Specifically set this to android. The default will cause you to run into ‘no_route’ errors.
-m This is the MCC for your country. In my case 641 is for Uganda. Use the site: http://mcclist.com/mobile-network-codes-country-codes.asp to locate yours
-n This is the MNC for your Telecom provider. Again, use the site: http://mcclist.com/mobile-network-codes-country-codes.asp to locate yours
-p This is your phone number. Include the country code specified in next option -C
-C This is the country telephone code. In my case 256 is for Uganda.
-r (sms|voice) This is method by which pin code will be sent to you

If execution of the above command is successful, you will receive, either a text message or voice call with the PIN code. Use this code to complete the registration process as follows:

yowsup-cli registration -d -E android -p 2567XXXXX -C 256 -R PIN-CODE

The arguments are similar to above, except for:
– R which allows you to register using the provided PIN-CODE

Once the command above has been executed successfully, the results displayed will look like the following

kind: free
pw: dfggHHSGGdIcdddRN567gjy=
price: US$0.99
price_expiration: 147567899
currency: USD
cost: 0.99
expiration: 4444444444.0
login: 256XXXXXXXXXX
type: new

Take note of the 2 fields: pw and login

Sending Messages

You should now be able to send messages using the command line. Test sending as follows:

yowsup-cli demos -d -l "256XXXXXXXX:dfggHHSGGdIcdddRN567gjy=" -s 256XXXXXXXXX "This is a test – Hello World"

The arguments explained:
-d For debugging
-l login. Enter in format [login:password]
-s The recipient’s phone number

At this point your recipient should be able to receive your message.

For monitoring with icinga2, you will need to create a script using the above command for sending messages. Make it executable and place it in location of your scripts. From, here, setup of icinga2 is like any other as shown in my previous article.

If you need more assistance or are interested in Linux and Open Source stuff, follow me @jzikusooka.

How to receive Linux server alerts on your phone via telegram

To monitor my Linux servers, I have been using icinga since its forking from the popular Nagios. Icinga has really matured over the last few years and currently at version 2.4.4, I would recommend anyone serious at network and server monitoring to check this open source project. Installation and setup of icinga2 is somewhat complex, but if you are an experienced command line sort of guy, its not that hard at all. In fact the introduction of icingaweb2 has made it possible to have an easy to use interface to setup your monitoring needs. I will not delve into the nitty gritty of install and setup. For that please take a look at the detailed documentation.

Several alerts are possible when using Icinga including e-mail, sms, XMPP, IRC, twitter etc. I wanted a way to get notified of host and service failures using telegram. Luckily, telegram provides an API to do just that.

The secret source in all of this; is to install a command line interface for telegram called telegram-cli . In order for telegram-cli to compile without any issues, ensure that all dependencies are installed

For Fedora:

sudo dnf -y install
lua-devel openssl-devel libconfig-devel readline-devel libevent-devel
jansson-devel python-devel

For Ubuntu/Debian:

sudo apt-get install
libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev
libevent-dev libjansson-dev libpython-dev make 

Now install telegram-cli

cd /usr/src && git clone –recursive https://github.com/vysheng/tg.git

Note: Make sure you add the recursive flag to git clone, otherwise make will fail

cd tg
./configure && make

The binary is under ./bin/telegram-cli. Simply create a symbolic link to it.

cd /usr/sbin && ln -s /usr/src/tg/bin/telegram-cli .

Thats it for the installation of telegram-cli. Please read the README file in the sources root folder, especially on how to use this application.

Icinga2 telegram-cli setup

First ensure that the user icinga (created during icinga install process) can send a message using telegram-cli. Remember all alerts go out under the icinga user, so you have to get this part working first, lest you spend hours troubleshooting.

Temporarily change the shell for icinga from ‘/sbin/nologin’ to ‘/bin/bash.’ Remember to change back to nologin for icinga user when testing is completed.

usermod -s /bin/bash icinga

Now change to user icinga: Assumming that you are root user, if not you will be prompted for a password, which you would setup as root.

su -l icinga
telegram-cli

Enter your phone number and SMS code sent when prompted

Then test to see if you can send a message:

telegram-cli -D -W -e "msg [PEER_NAME] 'Hello World'"

If it works, then you can proceed to configure icinga2.

Create notification script for services

cat > /etc/icinga2/scripts/notify_services_via_telegram.sh << EOF

#!/usr/bin/env bash

TELEGRAM_CMD=/usr/sbin/telegram-cli

TELEGRAM_OPTS=”-D -W”

TELEGRAM_PEER=[PEER_NAME]

TELEGRAM_MSG=$(cat <<TEMPLATE

[$HOSTALIAS] $NOTIFICATIONTYPE: $SERVICEDESC is $SERVICESTATE

TEMPLATE

)

$TELEGRAM_CMD $TELEGRAM_OPTS -e “msg $TELEGRAM_PEER ‘$TELEGRAM_MSG'”

EOF

Ensure that above script is executable:

chmod 755 /etc/icinga2/scripts/notify_services_via_telegram.sh

Proceed to configure commands, notifications, and hosts config files: Note: Am only setting up notifications for services. You can do the same for hosts information.

cat >> /etc/icinga2/conf.d/commands.conf <<EOF

/** Telegram */

object NotificationCommand “telegram-service-notification” {

import “plugin-notification-command”

command = [ SysconfDir + “/icinga2/scripts/notify_services_via_telegram.sh” ]

env = {

“NOTIFICATIONTYPE” = “$notification.type$”

“SERVICEDESC” = “$service.name$”

“HOSTALIAS” = “$host.display_name$”,

“HOSTADDRESS” = “$address$”,

“SERVICESTATE” = “$service.state$”,

“LONGDATETIME” = “$icinga.long_date_time$”,

“SERVICEOUTPUT” = “$service.output$”,

“NOTIFICATIONAUTHORNAME” = “$notification.author$”,

“NOTIFICATIONCOMMENT” = “$notification.comment$”,

“HOSTDISPLAYNAME” = “$host.display_name$”,

“SERVICEDISPLAYNAME” = “$service.display_name$”,

“USEREMAIL” = “$user.email$”

}

}

EOF

cat >> /etc/icinga2/conf.d/notifications.conf <<EOF

/** Telegram */

apply Notification “telegram-icingaadmin” to Service {

import “telegram-service-notification”

user_groups = host.vars.notification.telegram.groups

users = host.vars.notification.telegram.users

assign where host.vars.notification.telegram

}

EOF

To get alerts on services for a host, add the following stanza to the host configuration in /etc/icinga2/conf.d/hosts.conf

/* Telegram */

vars.notification[“telegram”] = {

groups = [ “icingaadmins” ]

}

Finally, check your config files

icinga2 daemon -C

Restart icinga if all is OK. You will now be notified via telegram when services fail for the above configured host.

How to install LetsEncrypt certificate on Fedora Linux

Here are some quick notes on how I installed letsencrypt certificates on a couple of my old Fedora servers. This is meant to get you started fairly quickly especially if you know how to install web servers on Linux systems. While there is a client already available for Fedora 23, I found that on older versions, the apache plugin for letsencrypt does not work. For instance, when you run the command:

./letsencrypt-auto --apache -d mydomainname.com, you get an error like:

The apache plugin is not working; there may be problems with your existing configuration.
The error was: NoInstallationError()

For earlier versions, you need to install the manual way i.e. generate a certificate. While that’s a few steps from the easy and automated promise of lets encrypt, you still can’t beat the price tag of Free!

Pull the sources for letsencrypt:

git clone https://github.com/letsencrypt/letsencrypt

Change to directory:

cd letsencrypt

Run the following command, and ofcourse replace the string mydomain.com with your domain:

./letsencrypt-auto certonly --standalone --agree-tos --email joe@mydomain.com -d mydomain.com

NOTE: For multiple domains, just add ‘-d mydomain.net’
Get help by running:

./letsencrypt-auto --help

If all goes well, you should see a congratulatory message, with the location of your free certificate chain! Use this in apache or nginx configuration

Keep in mind that the certificates are only vailid for three months, and you will need to do this again.

Uganda’s Digital TV Migration is complete but where’s the EPG Data?

Now that Uganda Communications Commission (UCC) says digital TV migration in the country is complete, its time to look at some of the benefits of using Digital TV.

One of the less advertised features of using digital versus Analogue TV is the extra data that comes with the signal. Among this data is the Electronic Program Guide (EPG) or in a lay man’s term – a listing of programmes and shows for each broadcaster with their respective airing times i.e. TV Guide. Forget that listing at the back of Uganda’s leading dailies – By the way, I can’t believe they still do that!

So why the fuss about EPG data? Other than the obvious, which is knowing when your favorite show will be on, EPG data can be used to schedule recordings on some smart devices. Knowing when a TV program will start and end is very central to most video recorder systems. Also, having this data automatically transmitted, takes the burden away from broadcasters from informing their viewers of any programming changes. It irks me every time I see “Coming Up,” “Up Next,” or “Programming guide” on TV.

As of today, the Free-to-Air mux(es) being used by Signet (474/594MHz) are not transmitting any EPG data. Only the Pay-TV providers are sending these data on the non-UCC frequencies.

It is time for Uganda’s TV broadcasters to start feeding EPG information along side their Free-to-Air TV channel streams. This is not an expensive proposition, and is in fact not optional for the Industry. This would be a small step, while we wait for all those extra channels resulting from the freed spectrum.

How to install a wireless hotspot with captive page on Linux using CoovaChilli

The purpose of this article is to demonstrate how you can turn a Linux based computer or laptop into a wireless hotspot where users can be authenticated via a captive portal page. For this task, the primary controller software will be CoovaChilli. This software is an ideal hotspot management solution for hotels, restaurants, supermarkets, parks, and any place offering WiFi Internet. Read more

Uganda’s analogue TV stations switched off in Kampala

In one of the first major moves to migrate the country to Digital TV, the Uganda Communications Commission (UCC) on Monday 15 June 2015, ordered broadcasters to switch off their analogue transmissions in and around Kampala. As expected most of the broadcasters complied, and Television consumers in this market who had not transitioned from their old analog TV sets will now have no TV.

It is too early to tell what sort of reaction Ugandans have about the switch-over. Also, the rest of the country still remains on Analogue, and will be phased into the migration on 31 of July and August 2015.

For now, the majority of TV channels, including NTV, NBS, WBS, Urban, UBC and others are using the 474MHz multiplex on the Free-To-Air feed around Kampala. For a detailed list of what channels are available, please check out Availability.

Why Uganda will most likely miss the Digital TV Switch-Over Deadline

With now only one month left to the deadline set for all countries to migrate from analogue to digital TV, Uganda will most likely miss the deadline, and instead opt for a post deadline switch-off date.

As we approach the internationally mandated Analogue TV switch-off date of 17 June 2015, Uganda’s major players on the transmission side are eerily quiet. Besides the media Ads from Uganda communications Commission (UCC) and jamboree marketing by Pay-TV subscription providers, there is practically no information on how far the roll out of digital TV is going. Instead Ugandan consumers are being urged to buy analogue-to-digital TV converter boxes that are certified by UCC. But what are consumers finding out after they purchase these boxes?

Kampala in the central region, was the first and still the only place where one can receive terrestrial over-the-air (OTA) digital TV feeds. The transmission in this area continues to be very spotty. If you are one of the few early adopters, and owns a digital TV tuner device, then you’ll have noticed that a number of TV channels on that platform are intermittent i.e. ‘On and off.’ As of Today, major television stations in Uganda like Urban, WBS TV, Bukedde-2 are not viewable on the distributed signal from Signet. For nearly two months even market leaders like NTV were off. For a full status on what station is on or off, take a look at: Available Digital TV Channels in Kampala.

Beyond Kampala, there is not much happening as Analogue TV continues to rein. The few Digital TV migration Ads that have been running on TV, radio and newspapers do not seem to be making any impact. Most people are just simply unaware of what is supposed to happen. But most importantly, these upcountry areas are not covered, so even if someone say Soroti town was to listen to UCC’s Ad, oblige and go out to buy an analogue-to-digital TV converter box, it would be useless as they would not be able to use it until the transmission rolls out to that region. Most people will not spend their hard earned money to buy these devices before the service is available in their area. So for most areas in the country, and depending on availability, Pay-TV is the only route to Digital migration at this time.

So what happens when the above deadline arrives?

The parties responsible for the Migration process will probably blatantly declare that the migration process is complete (Hoping that the upcountry areas at least major regions are covered). UCC is likely to ask Broadcasters to switch off Analogue TV transmissions for the Kampala area, but leave upcountry stations on. However, even in Kampala, the Analogue TV feeds are likely to be switched on again after some days of a blackout attempt. Why you ask?

The answer is very simple and very much similar to answers to other processes that required Ugandan citizens to spend more on infotainment – Remember the TV Tax? So the answer you guessed right is Politics. It is the political season here in Uganda, and a blanket and permanent switch-off of Analogue TV stations is likely to trigger a backlash and protest from several quarters. No Ugandan politician during this election season would want to be seen as the one depriving a citizen of their source of information. And by the way you know where those who don’t have Digital TV units now will run to for help on stopping the switch-off!

Also, as Uganda’s politicians return back to their rural constituencies to campaign for votes, they are likely to find a population that is already tired and angry of unfulfilled promises. Adding another ‘hot button’ like ‘You need to spend more money to continue watching your TV’ will not be easy. So Analogue TV switch off in these areas of Uganda will not occur for sometime. Remember, a lot of Ugandans have not been sensitized on why this Digital TV migration process is necessary.

Back in Kampala, most households (which don’t already have) will opt to buy a set top box aka ‘decoder’ from pay TV providers like Star, Go TV, Azam etc. In fact for the first few months, this will be the only way to ensure your favorite local TV channels are always available and not intermittent. This is because, even before the Digital TV migration process started, several of the Pay-TV providers signed monetary agreements with the broadcasters for their channels to be carried. This ensures that these feeds are always quickly worked on if they are having issues. Not quite so for the centrally distributed Free OTA Signal.

For the brave and those who will opt to buy analogue-to-digital TV converter boxes, expect the TV digital experience to remain similar to what it has been in the testing phase i.e. TV stations being on and off periodically.

So with Analogue TV likely to still be on, You might be wondering why any one would bother with all this ‘digito’ stuff. Well for one thing analogue TV must and will eventually go. It is not politics, but simply a technically efficient way for TV signals to be carried and distributed. But even if this reason is not convincing enough, compare the two types of broadcasts. If you watch your favourite local TV show in digital format, then you’ll agree with me that watching it in analogue format is not visually appealing at all. Really Digital TV is the way to go, there’s no turning back.

In conclusion, I doubt the major players see Free Over-the-Air Digital TV as a big priority. For the Pay-TV providers, luring consumers to a subscription model is now big business. And as long us the Free OTA transmissions are iffy-iffy then poorly informed consumers will continue to line up at Pay-TV dealer shops for those decoders.

If it can not do this at this late hour, UCC needs to prevail on Signet Uganda, the party responsible for Digital TV signal distribution and ask them to: step up and start informing the nation where Uganda stands on the Digital TV roll-out. The last time I checked, the information on Signet’s website was very dated and the last social media update on their twitter account i.e. @SignetUganda was on 11 December 2014!

Furthermore, UCC needs to know that its has failed Ugandans when it comes to a smooth transition from Analogue to Digital TV. No matter the country, people tend to warm up to a gradual and slow change but a drastic switch off is simply uncalled for especially given the 8+ years since the Ugandan government committed it self to this process. I understand, the constraints the commission has faced such as delayed funding, procurement, etc., but all of these issues should have been sorted out a long time ago.

Ugandans like citizens elsewhere deserve better on Digital TV migration, than these half-measure processes.

Use systemd in Linux like a Pro – A cheat sheet

As systemd becomes the default method of handling services in all major Linux distributions, below are some quick and easy-to-remember commands that will make you look like a pro.

systemctl

  • check for all running units
    systemctl
    TIP: To show all units, including in-active ones:
    systemctl list-unit-files
  • Check for failed units
    systemctl --failed
  • Start, stop, restart units
    systemctl start postfix.service
    systemctl restart postfix.service
    systemctl stop postfix.service
  • Check status of a specific unit
    systemctl status mysqld.service
    TIP: Use -l for detailed status
  • Enable or disable services
    systemctl enable firewalld.service
    systemctl disable NetworkManager.service
    TIP: If you disable a service, and it still runs,
    systemctl mask NetworkManager.service
    Use ‘unmask’ to restore it
  • See if a specific unit is enabled
    systemctl is-enabled iptables.service
  • Create a snapshot – useful for testing various targets
    systemctl snapshot example.snapshot
    TIP: To activate it:
    systemctl isolate example.snapshot
  • Reboot/poweroff/suspend your machine
    systemctl reboot
    systemctl poweroff
    systemctl suspend
  • Change current target – i.e. runlevel
    systemctl isolate graphical.target
  • To list current target
    systemctl list-units --type=target

systemd

  • See which units take a long time to start during boot up
    systemd-analyze blame
    TIP: You can plot the boot up using:
    systemd-analyze plot
  • See when a unit started and how long it took
    systemd-analyze critical-chain

journalctl

  • Create a running log like ‘tail -f /var/log/messages’
    journalctl -f -o cat --no-pager
  • Running log for a specific unit
    journalctl -f -o cat --no-pager -u httpd.service
  • See boot messages – like ‘dmesg’
    journalctl -b

Manage remote systems:
systemctl status sshd -H root@1.2.3.4

For detailed instructions on these and more commands, man as always is your best friend.

Uganda’s popular TV channels currently off the Digital TV (OTA) spectrum

Uganda’s traditionally most watched TV stations, Nation TV (NTV) and Wavah Broadcasting services (WBS) are currently off the UCC assigned Over-the-Air digital TV frequency, 474MHz. WBS TV has been off for nearly a month now, while NTV’s feed went off last week, with a brief return on Tuesday evening. Since, most Ugandans are still using analogue (and a few using Pay-TV-services), these blackouts on the Kampala Free-to-Air Digital TV transmission multiplex have gone pretty much unnoticed. Check out the current status for all Free-to-Air Digital TV Channels.

With all the questions surrounding the ability of Signet, the sole distributor of the Digital TV signals in Uganda , it is sad to see that some of Uganda’s major digital TV channels are off or barely on at this very late stage.
Signet, which was spawned from the national public broadcaster, Uganda Broadcasting Corporation (UBC) and contracted to handle the Digital TV signal distribution through out Uganda.

It would be nice to see all the parties responsible for digital TV migration in Uganda (i.e. Signet, Uganda Communications Commission, and broadcasters) aggressively updating the country, on where we are regularly especially now that we are quickly approaching the June switch off deadline.

How to configure nginx for use with WordPress and other CMS based websites

This is the second part of my Nginx tutorial. The first part covered the installation process. In this post, I will show you how to modify the default configuration and get your server ready to serve CMS based websites like WordPress, Drupal, Joomla, Gallery etc

Before delving into the configuration of nginx, it is important to ensure that all the prerequisite software is installed and properly configured. Like all of my tutorials, I am using Linux and specifically Fedora 20.

PHP

Install the following php and related modules:

yum install php php-fpm php-pecl-apcu php-pdo php-mcrypt php-common php-mysqlnd php-process php-gd php-pear php-pear-DB php-pgsql php-xml php-cli php-xmlrpc php-mbstring php-pecl-igbinary php-pecl-memcache php-pecl-memcached php-pecl-mongo php-pecl-jsonc

Edit the php configuration file:

vim /etc/php.ini

I recommend setting the following parameters in php.ini:

short_open_tag = On
date.timezone = Africa/Kampala (or your time zone)

Edit the php-fpm configuration file:

vim /etc/php-fpm.d/www.conf

Change the following options in www.conf:

[www]
listen = 127.0.0.1:9000
;listen.allowed_clients = 127.0.0.1
user = nginx
group = nginx

Change permissions of the php sessions directory:

chown nginx:nginx /var/lib/php

Now enable and start php-fpm service:

systemctl enable php-fpm.service && systemctl start php-fpm.service

OPENSSL

Install openssl if you plan on securing your server; which you should!

yum install openssl openssl-libs openssl-devel

Add ssl directory where certificate and key will be stored:

mkdir /etc/nginx/ssl

Generate self-signed SSL certificate and key for your webserver:

openssl req -new -x509 -out /etc/nginx/ssl/cert.pem -key /etc/nginx/ssl/cert.key -days 365

SPAWN-FCGI

Install spawn-fcgi, a simple program for spawning FastCGI processes:

yum install spawn-fcgi

Edit the environment file for spawn-fcgi:

vim /etc/sysconfig/spawn-fcgi

Make the following changes:

FCGI_SOCKET=/var/run/fcgiwrap.socket
FCGI_PROGRAM=/usr/sbin/fcgiwrap
FCGI_USER=nginx
FCGI_GROUP=nginx
FCGI_EXTRA_OPTIONS="-M 0700"
OPTIONS="-u $FCGI_USER -g $FCGI_GROUP -s $FCGI_SOCKET -S $FCGI_EXTRA_OPTIONS -F 1 -P /var/run/spawn-fcgi.pid -- $FCGI_PROGRAM"

Enable and start spawn-fcgi.service:

systemctl enable spawn-fcgi.service && systemctl start spawn-fcgi.service

FCGIWRAP

Install fcgiwrap, a simple FastCGI wrapper for CGI scripts:

cd /usr/src

Download fcgiwrap sources:

git clone https://github.com/gnosek/fcgiwrap.git
cd /usr/src/fcgiwrap
autoreconf -i
./configure --prefix=/usr
make && make install

CONFIGURATION

Nginx’s configuration files are located under /etc/nginx. And as specified by the installation configure command in the previous post, the main configuration file is: /etc/nginx/nginx.conf. This is where I will make most of my changes.

vim nginx.conf

Add the following to nginx.conf and save it:

user nginx;
worker_processes 1;
#
events {
worker_connections 1024;
}
#
http {
include mime.types;
include conf.d/*.conf;
include sites-enabled/*;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
sendfile on;
keepalive_timeout 65;
#
server {
listen 80;
server_name localhost;
root html;
index index.html index.htm index.php;
autoindex on;
access_log /var/log/nginx/localhost.access.log main;
#
location / {
}
#
error_page 500 502 503 504 /50x.html;
#
location = /50x.html {
}
#
location ~ \.php$ {
include includes/php_params;
}
#
location ~* \.(cgi|chi)$ {
include includes/cgi_params;
}
# Add xmlrpc scgi support
#
location ~ ^/RPC2$ {
scgi_pass localhost:5000;
include scgi_params;
}
}
#
# HTTPS server
#
server {
listen 443 ssl;
server_name localhost;
root html;
index index.html index.htm index.php;
#
ssl_certificate ssl/cert.pem;
ssl_certificate_key ssl/cert.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
#
location / {
}
#
location ~ \.php$ {
include includes/php_params;
}
#
location ~* \.(cgi|chi)$ {
include includes/cgi_params;
}
}
}

To get details on what these directives exactly mean and the syntax used above, visit the Nginx documentation

NOTES:

Nginx is pretty picky when it comes to Syntax, so:

– The location directive is placed within a server directive.
– Also, all directives must end with a semicolon.

Like other similar programs in UNIX, you can split the configuration file into several files using the parameter: include as shown in the above file. This makes maintenance and packaging of these files easier.

Create other configuration directories:

mkdir /etc/nginx/{conf.d,includes,sites-enabled}

Add the following files to the includes directory:

vim /etc/nginx/includes/php_params

gzip off;
fastcgi_pass unix:/var/run/fcgiwrap.socket;
fastcgi_index index.cgi;
#
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
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 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;

vim /etc/nginx/includes/cgi_params

fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
#
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
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 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;

VIRTUAL HOSTS

Now let’s configure a virtual host. In this tutorial, I use example.com as the domain name.

vim /etc/nginx/sites-enabled/example.com

server {
listen 80;
#
server_name zikusooka.com www.zikusooka.com;
root html/vhost.example;
index index.html index.htm index.php;
#
location / {
}
#
location ~ \.php$ {
include includes/php_params;
}
#
location ~* \.(cgi|chi)$ {
include includes/cgi_params;
}
}

WEB CONTENT

Add an index file to the main server’s root directory, for example:

vim /usr/share/nginx/html/index.html

Add the following and save (This is just for testing, any HTML web page should work):

<HTML>
<B>Hello World. Welcome to my Nginx web server!</B>
<HTML>

Create the document root directory for your virtual host:

mkdir /usr/share/nginx/html/example.com

Add your document root in the above created directory. For Example create a file named index.php.

vim /usr/share/nginx/html/example.com/index.php

Add the following and save (This is just to test php, so any simple php page should work):

<?
phpinfo();
?>

TESTING

Finally, restart nginx web server:

systemctl start nginx

If all goes well, you should now be able to browse html, php, and cgi pages on your server. You can then proceed to installing your WordPress or other content management system.

Scroll to top