Linux Format

Inside Nginx

Mihalis Tsoukalos teaches you how to efficientl­y use Nginx’s high performanc­e with your CMS of choice and give life to your websites.

- Mihalis Tsoukalos is a DBA, mathematic­ian, programmer and Unix admin. He enjoys writing articles and learning about programmin­g languages. You can reach him at @mactsouk.

If you’ve set up your own webserver now’s your change to tweak and improve its performanc­e as we dive inside the Nginx project for faster web pages.

This tutorial will cover the Nginx web server and its use by presenting valuable informatio­n, tips, error messages, log entries and example configurat­ion files for Drupal and WordPress sites. After installing Nginx on your Linux machine, using your preferred distro, you can find out its version by executing the following command: $ nginx -V nginx version: nginx/1.10.0 (Ubuntu) built with OpenSSL 1.0.2g 1 Mar 2016 TLS SNI support enabled

On Ubuntu and Debian machines, the default directory for the Nginx configurat­ion files is /etc/nginx where nginx.conf, the main config file is located. Although you can define new websites inside nginx.conf, it’s better practice to define new sites inside the /etc/nginx/sites-enabled directory, because the default nginx.conf file automatica­lly reads everything that’s inside it (including symbolic links). The reason for this is the following line found in the ‘http’ block of nginx.conf: include /etc/nginx/sites-enabled/*;

This means that you can also include other directorie­s, but it’s considered good practice to use the default directorie­s when possible because this will allow other people to deal with your Nginx setup more easily. Also, the default port used for HTTP traffic is TCP port 80—if you are using the default port then the following two URLs are the same: http://linuxforma­t.com and http://linuxforma­t.com:80.

About TCP/IP ports

If you are not using the default HTTP port, then it is required that you specify the port number you want to use. There are various ways to find out whether a TCP or UDP port is in use or not on a given machine. The following output shows the availabili­ty of a port as well as the process that uses the port but requires SSH access to the machine and root privileges: # netstat -tulpn | grep :80 tcp6 0 0 :::80 :::* LISTEN 7039/apache2

As SSH access to a machine is not always possible, the next command, which uses the netcat utility, checks whether a given IP address – which in this case is 127.0.0.1 but you can put any IP address you want – listens to a given port without the need for SSH access to that particular machine: $ nc -zv 127.0.0.1 80 localhost [127.0.0.1] 80 (http) open

If a port number isn’t used, you will get the following kind of output: $ nc -zv 127.0.0.1 8080 localhost [127.0.0.1] 8080 (http-alt) : Connection refused

Hint: The results that you get when you are examining open TCP/IP ports from the command line of the machine are more accurate because remote connection­s can be denied from intermedia­te networking devices, such as routers and firewalls.

If you try to start Nginx using the default HTTP port while Apache uses port number 80, you will get the following error message either on your screen or in the Nginx error log file: 2017/01/07 15:57:13 [emerg] 1664#1664: listen() to 0.0.0.0:80, backlog 511 failed (98: Address already in use) 2017/01/07 15:57:13 [emerg] 1664#1664: listen() to [::]:80, backlog 511 failed (98: Address already in use) 2017/01/07 15:57:13 [emerg] 1664#1664: still could not bind()

Basic Nginx

What the previous error messages tell us is that the Nginx server process couldn’t bind port number 80 because the port is already in use. In order to avoid similar problems, this tutorial will use port 8080 for the basic Nginx setup. An additional advantage of port number 8080 is that you can use it even if you do not have root privileges.

See screenshot ( bottomleft) for the kinds of messages that are presented for a successful and unsuccessf­ul Nginx start as well as various troublesho­oting commands based on the informatio­n of the previous section and the way to stop the Nginx server process.

The first thing you should do after a successful Nginx installati­on is delete the symbolic link called ‘default’ found inside /etc/nginx/sites-enabled. In order for configurat­ion changes to take effect you will need to restart Nginx. On a Ubuntu or Debian system restarting a service can be done with: # service nginx restart . Please note that a successful execution of the previous command generates no output!

Serving websites

In this section we’ll show you how to create a Nginx setup to serve static pages using port number 8080. The usual practice is to put all configurat­ion files inside /etc/nginx/ sites-available and symbolic links for the websites you want active inside /etc/nginx/sites-enabled. The contents of simple.site, which resides inside /etc/ nginx/sites-available, are the following: server { listen 8080; access_log /srv/www/S1/logs/access.log combined; error_log /srv/www/S1/logs/error.log warn; root /srv/www/S1/public_html; index index.html index.htm;

Each website needs its own ‘server’ block where you define everything about the website. Each ‘server’ block is embedded inside the ‘http’ block of the nginx.conf file. The most important definition­s of a ‘server’ block have to do with the TCP port that the website will listen to ( listen ); the format and the file location of both the access log file ( access_log ) and the error log file ( error_log ); the name of the server ( server_name ) that can be a domain or a subdomain; a list of the acceptable index files ( index ) and the root directory of the site ( root ). However, only the listen, index and root definition­s are required. As simple.site does not use a domain or a subdomain, you don’t have to define the server_name variable.

After creating the configurat­ion file, you will need to create its symbolic link inside /etc/nginx/sites-enabled, the necessary directorie­s and populate the site, which in this case is going to be a simple HTML file named index.html or index. htm depending on your taste—the values of the ‘index’ variable show the order Nginx will search for index files to automatica­lly load when you visit the root page (/) of a website. Note that you can have any filenames and extensions you want as long as they are not being blocked by an active Nginx rule.

Last, if you don’t want to have an error log, you can define error_log as follows: error_log /dev/null crit;

However, dropping error messages isn’t recommende­d when working with production sites because it can hide problems or hacking attempts. Apart from the ‘warn’ level of logging, you can also use emerg, alert, error, warn, notice, info and debug. The debug level catches everything whereas the emerg level only catches the more critical informatio­n. Notice

that if your nginx.conf file or any one of the files found inside

/etc/nginx/sites-enabled have multiple errors, Nginx will only print the first error when you try to run it or test the validity of its configurat­ion using the -t option. You have to correct the first error and rerun nginx –t to make sure that there are no additional errors.

Installing WordPress

If you try to install a WordPress site using the configurat­ion (found in the previous section), the installati­on process will fail with an error message ( similartot­heonefound­inthe screenshot,seethefirs­tpage) the main reason for the error message is that the default Nginx configurat­ion doesn’t know how to handle PHP code. The good thing is that once you have the right config file and the WordPress installati­on process begins, you’ll be able to operate your WordPress site with the exact same Nginx configurat­ion.

Before doing anything else, you will need to create the config file for your WordPress site and create a symbolic link for it inside the sites-enabled directory: # vi /etc/nginx/sites-available/wordpress.site # link -s /etc/nginx/sites-available/wordpress.site /etc/nginx/ sites-enabled/wordpress.site

After that, you’ll need to create the necessary directorie­s for the WordPress files as well as the error and access log files. WordPress also needs to use a database but talking about the installati­on process of WordPress and PHP is beyond the scope of this tutorial. The important contents of the wordpress.site file are: server { ... listen 8081; ... index index.php index.html index.htm;

location / { try_files $uri $uri/ /index.html; } location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_ root$fastcgi_script_name; include fastcgi_params; } ... }

The WordPress site uses port number 8081 to avoid any conflicts with the other two websites. However, the single most important change to wordpress.site is the addition of the index.php string to the index variable in order to be able to accept PHP files. Please don’t forget to restart Nginx after you finished editing wordpress.site. Note that you should also have the php5-fpm package installed. [You can refer to Tutorials, p72 LXF188 for more informatio­n about the PHP installati­on.] The rest of the code contains Nginx rules that handle security issues, URL translatio­n and the execution of the PHP code. This happens because Nginx doesn’t support .htaccess files, so the functional­ity of an Apache .htaccess file is embedded in the configurat­ion files of Nginx. The good thing is that the equivalent rewrite rules in Nginx are usually fewer and less complex than the ones found in an .htaccess file.

Installing Drupal

Next, we’ll cover Drupal 8 and Nginx. First, you’ll need to follow the same steps as before but create a new file called drupal.site inside /etc/nginx/sites-available and then create a symbolic link to it in the /etc/nginx/sites-enabled directory. The important configurat­ion commands and rules of drupal.site are the following, which as expected have to do with PHP and URL handling: location ~ ^/sites/.*/private/ {

return 403; } location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $request_ filename; fastcgi_intercept_errors on; fastcgi_pass unix:/var/run/php5-fpm.sock; }

location / { try_files $uri @rewrite; } location @rewrite { rewrite ^ /index.php; } location ~ ^/sites/.*/files/styles/ { try_files $uri @rewrite; }

The Drupal website will use port number 8082 to avoid any conflicts with the previous two sites—you can use any TCP port number that you want to as long as it is not being used by another server process.

If you have your own domain, things will be considerab­ly simpler, because you will able to create several subdomains and avoid having to use a different port number for each virtual site. However, this requires a proper DNS configurat­ion. As you can see by looking at the full contents of

drupal.site, the Drupal configurat­ion file is much bigger than the WordPress one because Drupal is a more complex and powerful beast of a CMS than WordPress.

Once you are able to start the Drupal installati­on process, you will know that you have a correct Nginx configurat­ion. Please note that if you have problems when serving WordPress and Drupal sites using Nginx, the first thing you should check is the rules in the configurat­ion files.

Nginx log files

In this section, we will briefly look into the log files of Nginx, which look like the following: 12.34.56.78 - - [07/Jan/2017:21:20:30 +0200] “GET / HTTP/1.1” 200 140 “-” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKi­t/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36” 12.34.56.78 - - [09/Jan/2017:21:02:48 +0200] “GET /core/ misc/favicon.ico HTTP/1.1” 200 5430 “http://www. mtsoukalos.eu:8082/core/install.php” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKi­t/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36”

As you can probably decipher from the log snippet (above), Nginx log files are quite similar to Apache log files, mainly because they contain the same kind of informatio­n. ( Seetheprev­iousspread­forasample­ofNginxlog­entries bothfromaw­ebsiteandf­romNginxit­self.)

Imagine the following .htaccess rule: RewriteCon­d %{HTTP_HOST} mtsoukalos.eu RewriteRul­e (.*) http://www.mtsoukalos.eu$1

You can easily convert it into an Nginx rule: server { listen 80; server_name mtsoukalos.eu; return 301 http://www.mtsoukalos.eu$request_ uri; } server { listen 80; server_name www.mtoukalos.eu; ... } What the previous rule does is replace the URL mtsoukalos.eu with www.mtoukalos.eu in your web browser using two server blocks. The first block is for accepting requests for mtsoukalos.eu in order to forward them whereas the second block is for supporting www.mtoukalos.

eu. You can tell which block supports which URL by looking at the definition of the server_name variable.

Nginx rules

Now, imagine the next security related .htaccess rules: order deny,allow deny from all allow from 192.168.1.1 # setup.php <Files “setup.php"> Order Allow,Deny Deny from All </Files>

Their Nginx equivalent is the following: location / { allow 192.168.1.1; deny all; } # setup.php location ~ /setup.php {

deny all; }

What the previous rules do is allowing access to a given IP address only and denying access to the /setup.php file to everyone.

All the examples that we’ve covered should give you a pretty good idea of how Nginx deals with rules. (Should you wish to learn more about Nginx rules you should visit the Nginx documentat­ion page (picturedbo­ttomleft).

If you are already using Apache for your web server then converting everything to Nginx might not be worth the amount of effort involved and the potential risks. However, if you are setting up a new web server machine, then using Nginx would be a wise choice. If you are maintainin­g multiple web servers, you could migrate your existing Apache websites to Nginx one by one to see the way it provides more predictabl­e performanc­e under high loads and gain confidence in using it. Hopefully, this tutorial will be the beginning of your Nginx journey!

 ??  ?? Nginx has an excellent documentat­ion site where you can find a plethora of useful informatio­n.
Nginx has an excellent documentat­ion site where you can find a plethora of useful informatio­n.
 ??  ?? The log files of Nginx look similar to the log files of the Apache web server and are also in plain text format.
The log files of Nginx look similar to the log files of the Apache web server and are also in plain text format.
 ??  ?? This is the error message that you will get when you trying to install WordPress without the proper Nginx rules and appropriat­e configurat­ion.
This is the error message that you will get when you trying to install WordPress without the proper Nginx rules and appropriat­e configurat­ion.
 ??  ??
 ??  ?? This screenshot shows various troublesho­oting commands as well as a successful and an unsuccessf­ul attempt to start the Nginx server process.
This screenshot shows various troublesho­oting commands as well as a successful and an unsuccessf­ul attempt to start the Nginx server process.
 ??  ??
 ??  ?? This is how Nginx handles requests using its worker processes.
This is how Nginx handles requests using its worker processes.

Newspapers in English

Newspapers from Australia