Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

Running Drupal 7.7 On Nginx (LEMP) On Debian Squeeze/Ubuntu 11.04


This tutorial shows how you can install and run a Drupal 7.7 web site on a Debian Squeeze or Ubuntu 11.04 system that has nginx installed instead of Apache (LEMP = Linux + nginx (pronounced “engine x”) + MySQL + PHP). In addition to that I will also show you how you can use the Drupal Boost plugin with nginx. nginx is a HTTP server that uses much less resources than Apache and delivers pages a lot of faster, especially static files.

I do not issue any guarantee that this will work for you!

 

1 Preliminary Note

I want to install Drupal in a vhost called www.example.com/example.com here with the document root /var/www/www.example.com/web.

You should have a working LEMP installation, as shown in these tutorials:

  • Installing Nginx With PHP5 And MySQL Support On Debian Squeeze
  • Installing Nginx With PHP5 (And PHP-FPM) And MySQL Support On Ubuntu 11.04

A note for Ubuntu users:

Because we must run all the steps from this tutorial with root privileges, we can either prepend all commands in this tutorial with the string sudo, or we become root right now by typing

sudo su

 

2 Installing APC

APC is a free and open PHP opcode cacher for caching and optimizing PHP intermediate code. It’s similar to other PHP opcode cachers, such as eAccelerator and XCache. It is strongly recommended to have one of these installed to speed up your PHP page.

APC can be installed as follows:

apt-get install php-apc

If you use PHP-FPM as your FastCGI daemon (like in Installing Nginx With PHP5 (And PHP-FPM) And MySQL Support On Ubuntu 11.04), restart it as follows:

/etc/init.d/php5-fpm restart

If you use lighttpd’s spawn-fcgi program as your FastCGI daemon (like in Installing Nginx With PHP5 And MySQL Support On Debian Squeeze), we must kill the current spawn-fcgi process (running on port 9000) and create a new one. Run

netstat -tap

to find out the PID of the current spawn-fcgi process:

root@server1:~# netstat -tap
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 *:sunrpc                *:*                     LISTEN      734/portmap
tcp        0      0 *:www                   *:*                     LISTEN      2987/nginx
tcp        0      0 *:ssh                   *:*                     LISTEN      1531/sshd
tcp        0      0 *:57174                 *:*                     LISTEN      748/rpc.statd
tcp        0      0 localhost.localdom:smtp *:*                     LISTEN      1507/exim4
tcp        0      0 localhost.localdom:9000 *:*                     LISTEN      1542/php5-cgi
tcp        0      0 localhost.localdo:mysql *:*                     LISTEN      1168/mysqld
tcp        0     52 server1.example.com:ssh 192.168.0.198:2462      ESTABLISHED 1557/0
tcp6       0      0 [::]:www                [::]:*                  LISTEN      2987/nginx
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN      1531/sshd
tcp6       0      0 ip6-localhost:smtp      [::]:*                  LISTEN      1507/exim4
root@server1:~#

In the above output, the PID is 1542, so we can kill the current process as follows:

kill -9 1542

Afterwards we create a new spawn-fcgi process:

/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data -f /usr/bin/php5-cgi -P /var/run/fastcgi-php.pid

3 Installing Drupal

The document root of my www.example.com web site is /var/www/www.example.com/web – if it doesn’t exist, create it as follows:

mkdir -p /var/www/www.example.com/web

Next we download Drupal from http://ftp.drupal.org/files/projects/drupal-7.7.tar.gz and place it in our document root:

cd /tmp
wget http://ftp.drupal.org/files/projects/drupal-7.7.tar.gz
tar xvfz drupal-7.7.tar.gz
cd drupal-7.7/
mv * /var/www/www.example.com/web/

It is recommended to make the document root and the Drupal files in it writable by the nginx daemon which is running as user www-data and group www-data:

chown -R www-data:www-data /var/www/www.example.com/web

If you haven’t already created a MySQL database for Drupal (including a MySQL Drupal user), you can do that as follows (I name the database drupal in this example, and the user is called drupal_admin, and his password is drupal_admin_password):

mysqladmin -u root -p create drupal

mysql -u root -p

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON drupal.* TO ‘drupal_admin’@’localhost’ IDENTIFIED BY ‘drupal_admin_password’;
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON drupal.* TO ‘drupal_admin’@’localhost.localdomain’ IDENTIFIED BY ‘drupal_admin_password’;

FLUSH PRIVILEGES;

quit;

Next we create an nginx vhost configuration for our www.example.com vhost in the /etc/nginx/sites-available/ directory as follows:

vi /etc/nginx/sites-available/www.example.com.vhost

server {
       listen 80;
       server_name www.example.com example.com;
       root /var/www/www.example.com/web;
       if ($http_host != "www.example.com") {
                 rewrite ^ http://www.example.com$request_uri permanent;
       }
       index index.php index.html;
       location = /favicon.ico {
                log_not_found off;
                access_log off;
       }
       location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
       }
       # Make sure files with the following extensions do not get loaded by nginx because nginx would display the source code, and these files can contain PASSWORDS!
        location ~* \.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|\.php_ {
                deny all;
        }
       # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
       location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
       }
       location / {
                try_files $uri $uri/ /index.php?$args;
       }
       location ~*  \.(jpg|jpeg|png|gif|css|js|ico)$ {
                expires max;
                log_not_found off;
       }
       location ~ \.php$ {
                try_files $uri =404;
                include /etc/nginx/fastcgi_params;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       }
}

To enable that vhost, we create a symlink to it from the /etc/nginx/sites-enabled/ directory:

cd /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/www.example.com.vhost www.example.com.vhost

Reload nginx for the changes to take effect:

/etc/init.d/nginx reload

Now we can launch the web-based Drupal installer by going to http://www.example.com – select Standard and click on Save and continue:

1

Select your desired language next:

2

Next fill in the database details:

3

Drupal is now being installed:

4

Next fill in some details regarding your site (like site name, email address) and specify an admin user and password:

5

Next fill in some details regarding your site (like site name, email address) and specify an admin user and password:

6

That’s it! Drupal is now installed. Click on the Visit your new site. link…

7

… to see your new Drupal web site:

8

The first thing you should do is enable clean URLs. Go to Configuration > Clean URLs:

9

Check the Enable clean URLs checkbox and click on Save configuration:

10

If you have already created some content on your Drupal site, you can now browse that content. If everything goes well, you should now see clean URLs in the browser’s address bar (it is also possible to define URL aliases in Drupal to create speaking URLs):

12

There’s no need to specify any rewrite rules in your nginx configuration for the clean URLs to work! That is because of this cool little line in our vhost configuration /etc/nginx/sites-available/www.example.com.vhost:

try_files $uri $uri/ /index.php?q=$uri;

If you don’t want to use the Boost cache plugin, you are finished now! The next chapter deals with the Boost plugin.

4 Installing And Configuring Boost

Go to http://drupal.org/project/boost and download the Boost module (http://ftp.drupal.org/files/projects/boost-7.x-1.x-dev.tar.gz) to your computer.

Then log into Drupal as the admin user and go to the Modules section (http://www.example.com/admin/modules/install). Select the Boost module from your computer’s hard drive by clicking on the Browse… button and then click on the Install button:

13a

After the successful installation you will see this screen. Click on the Enable newly added modules link to enable Boost:

13b

This will bring you to the list of modules (http://www.example.com/admin/modules). Scroll down to the Boost module, check it and click on Save configuration:

14

Afterwards, you should find a Configure link behind the Boost module. Click on that link to start the Boost configuration:

15

Now in the Boost configuration (http://www.example.com/admin/config/system/boost), you should find yourself on the BOOST SETTINGS tab. It is ok to accept the default values – click on Save configuration:

16

17

Go to the CACHE EXPIRATION tab. Again, the default settings should be ok, so click on Save configuration again:

18

Next go to the FILE SYSTEM tab. Make sure you have cache in the Root cache directory field (that should be the default value) – this translates to our cache directory /var/www/www.example.com/web/cache. The other default values are ok as well, so click on Save configuration:

19

You can ignore the .HTACCESS tab because it generates rewrite rules for Apache, but we are on nginx.

Now we must reconfigure our nginx vhost.

Open /etc/nginx/sites-available/www.example.com.vhost

vi /etc/nginx/sites-available/www.example.com.vhost

… and replace

[...]
       location / {
                try_files $uri $uri/ /index.php?$args;
       }
[...]

… with:

[...]
       location @nocache {
                try_files $uri $uri/ /index.php?$args;
       }
[...]

Then add the following new location / { } section:

[...]
       location / {
                if ($query_string ~ ".+") {
                        return 405;
                }
                # pass requests from logged-in users to Apache
                if ($http_cookie ~ "DRUPAL_UID" ) {
                        return 405;
                } # pass POST requests to Apache
                if ($request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                error_page 405 = @nocache;
                # do not allow browsers to cache HTML
                add_header Expires "Sun, 19 Nov 1978 05:00:00 GMT";
                add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
                # serve requested content from the cache if available, otherwise pass the request to Apache
                try_files /cache/normal/$host/${uri}_.html /cache/perm/$host/${uri}_.css /cache/perm/$host/${uri}_.js /cache/$host/0$uri.html /cache/$host/0${uri}/index.html @nocache;
       }
[...]

The complete file looks as follows:

server {
       listen 80;
       server_name www.example.com example.com;
       root /var/www/www.example.com/web;
       if ($http_host != "www.example.com") {
                 rewrite ^ http://www.example.com$request_uri permanent;
       }
       index index.php index.html;
       location = /favicon.ico {
                log_not_found off;
                access_log off;
       }
       location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
       }
       # Make sure files with the following extensions do not get loaded by nginx because nginx would display the source code, and these files can contain PASSWORDS!
        location ~* \.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|\.php_ {
                deny all;
        }
       # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
       location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
       }
       location / {
                if ($query_string ~ ".+") {
                        return 405;
                }
                # pass requests from logged-in users to Apache
                if ($http_cookie ~ "DRUPAL_UID" ) {
                        return 405;
                } # pass POST requests to Apache
                if ($request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                error_page 405 = @nocache;
                # do not allow browsers to cache HTML
                add_header Expires "Sun, 19 Nov 1978 05:00:00 GMT";
                add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
                # serve requested content from the cache if available, otherwise pass the request to Apache
                try_files /cache/normal/$host/${uri}_.html /cache/perm/$host/${uri}_.css /cache/perm/$host/${uri}_.js /cache/$host/0$uri.html /cache/$host/0${uri}/index.html @nocache;
       }
       location @nocache {
                try_files $uri $uri/ /index.php?$args;
       }
       location ~*  \.(jpg|jpeg|png|gif|css|js|ico)$ {
                expires max;
                log_not_found off;
       }
       location ~ \.php$ {
                try_files $uri =404;
                include /etc/nginx/fastcgi_params;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       }
}

Then reload nginx:

/etc/init.d/nginx reload

That’s it. Now after the first anonymous users have visited your site, you should see your cache directory fill:

ls -l /var/www/www.example.com/web/cache/normal/www.example.com/

root@server1:~# ls -l /var/www/www.example.com/web/cache/normal/www.example.com/
total 36
-rw-rw-r– 1 www-data www-data 11465 Aug 10 11:59 _.html
-rw-rw-r– 1 www-data www-data  9619 Aug 10 11:59 nginx-413-request-entity-too-large_.html
-rw-rw-r– 1 www-data www-data  9628 Aug 10 12:00 postfix-mail-loops-back-to-myself_.html
root@server1:~#

Browse your site as an anonymous user and take a look at the source code. For pages that are served from the cache, you should see a comment at the end of the source code saying <!– Page cached by Boost –>.

20

Drupal’s cron will take care of cleaning up the cache directory, i.e., if you have told Boost to cache for one hour, cached files older than one hour will be deleted from the cache. Also, if you update your site (insert or update a page or add a comment), the cache will be cleaned as well to make sure users don’t see outdated content.

You can now use a tool like Apache Benchmark (ab) to test your site’s performance, and you should see that it is able to handle much more requests per second than before.

 

  • Drupal: http://drupal.org/
  • Boost: http://drupal.org/project/boost
  • nginx: http://nginx.org/
  • nginx Wiki: http://wiki.nginx.org/
  • Debian: http://www.debian.org/
  • Ubuntu: http://www.ubuntu.com/

Comments

comments