Skip to content

Home

Making your BASH history more efficient

There are several ways to improve how you troubleshoot a system. One of the things I consider to be important is the BASH history. Here you can see what commands were executed. Though as default you can’t see when, or ignore certain things, like duplicate commands. Here’s a little guide to show you how.

Notice: To make these features a permanent solution, open up your /etc/profile, and add the lines to the bottom of the file. Save and close it. The next time you log in the functions should be working as you specified them!

HISTTIMEFORMAT

A simple yet effective little trick is to change the format of the output the command history spits out. In my case it comes to good use when troubleshooting a system, wanting to find out if errors in the system log match up with commands executed at that time. To enable the feature in your current terminal, run:

export HISTTIMEFORMAT="%h %d %H:%M:%S> "

So the output from history that was looking like this:

[jorge@ashitaka ~]$ history
1 ls
2 echo "Hello"
3 pwd
...

Now looks like this:

[jorge@ashitaka ~]$ history
1 Mar 24 12:53:35> ls
2 Mar 24 12:53:36> echo "Hello"
3 Mar 24 12:53:37> pwd
...

HISTCONTROL

The variable HISTCONTROL can do a few things, like ignoring duplicates if they are in a row and erasing duplicates. The difference here is that by ignoring duplicates, it will remove duplicates only if they are in a row, while erasing duplicates, it will remove previous commands from the history file. Let’s give an example:

ignoredups

First run:

export HISTCONTROL=ignoredups

The output that looked like this:

[jorge@ashitaka ~]$ history
1 pwd
2 echo "Hello"
3 ls -l
4 ls -h
5 pwd
6 pwd
...

Will now look like this:

[jorge@ashitaka ~]$ history
1 pwd
2 echo "Hello"
3 ls -l
4 ls -h
5 pwd
...

erasedups

erasedups means that if you executed the same command previously, that entry will be erased, substituted by the newly run command. Generally not recommended though. If you still wish to do so, it can be done by running the following line:

export HISTCONTROL=erasedups

So a history that looked like this:

[jorge@ashitaka ~]$ history
1 pwd
2 echo "Hello"
3 ls -l
4 ls -h
5 pwd
...

After the export, will now look like this when we run the command pwd again:

[jorge@ashitaka ~]$ history
1 echo "Hello"
2 ls -l
3 ls -h
4 pwd
...

ignorespace

If you want full control over which commands will be stored by history and which will not be stored, set HISTCONTROL to ignorespace:

export HISTCONTROL=ignorespace

So out of these commands:

ls -la
 du -h
ps

Only these will show:

[jorge@ashitaka ~]$ history
1 ls -la
2 ps
...

ignoredups and ignorespace

To use both of these features, simply use:

export HISTCONTROL=ignoreboth

HISTIGNORE

The variable HISTIGNORE will help you tell history which commands to ignore, meaning that they shouldn’t be picked up by the BASH history. For instance, let’s say that I want the commands df and free to be ignored, including optional flags:

export HISTIGNORE="df*:free*"

HISTSIZE

Setting how many lines of history to store is always a nice feature:

export HISTSIZE=10000

Thanks to pkhamre for suggesting to include HISTCONTROL and HISTIGNORE. ;)

Introduction to screen

screen is for many people an unknown program and tool, but those who do know it consider it to be an essential one. This is because of the functionality of the program, that can end up saving you a lot of work and time. You can run any number of console-based applications – editors, mail clients, browsers, in just a single terminal. Sometimes it’s useful to have a terminal for each console-based application you’re running, but sometimes not, obviously.

For my part, the main reason for me using screen is the ability to decouple the terminal emulator from the running programs. In other words, I can detach and reattach things as I please. To put it in simple terms; it’s a tool for session management. Let’s go ahead with an example.

You are logged into your remote server via SSH, working on some configuration file, when suddenly you lose connection to it. Almost done, having spent hours, you grab your laptop in anger and smack the closest unfortunate person next to you. Not only have you lost valuable work, but soon enough people with shields, guns and helmets will come after you. Imagine, with screen, it could have been avoided! Had you been editing the configuration file within a screen, and should you have lost connection, the editing would still be in an active screen session, allowing you to detach and reattach the screen to your terminal once you logged back in.

Let’s have a closer look at what we can do with screen.

Starting screen

screen

If installed, you probably won’t get a message about having entered a screen session, but I’m sure you have. Everything functions just like a normal shell, except for a few special characters. screen uses the command Ctrl-A as a signal to screen instead of the shell.

To see the help page for screen, press Ctrl-A, then press ?. In other words:

^A ?

As you can see here, Ctrl is represented by the ^, A is A, and well, you get the rest.

To start a program directly into screen, just type screen . Let’s use top as an example.

Using screen

Fire it up:

screen top

top is started in the usual way, just inside a screen session. To detach the session and let it run in the background, use Ctrl-a d:

Ctrl-a d (^a d)

Once your session is detached you can list the available screen sessions by using:

screen -ls

The output you’ll see will be something along the lines of:

[jorge@cat ~]$ screen -ls
There is a screen on:
    26606.pts-39.cat    (Detached)
1 Socket in /var/run/screen/S-jorge.

To reattach the screen session to your current terminal, you can use screen -dr . In this case it would be:

screen -dr 26606

This brings up an interesting question though. How can you differentiate what multiple screen sessions are holding, if you can only read the process number? Easy – you give each screen session a name. For most people, a name is easier to remember than a number. So, we start a new screen, in which we’re going to open an IRC client called irssi. Let’s use -S:

screen -S irc irssi

Entering irssi, we detach the session with Ctrl-a d, and do a screen -ls to see what we’ve got now:

[jorge@cat ~]$ screen -ls
There are screens on:
    26606.pts-39.cat    (Detached)
    26702.irc    (Detached)
2 Sockets in /var/run/screen/S-jorge.

There you clearly see the name irc that we entered earlier, and the session holding top, which we started up even before being able to specify a name. Pretty handy, huh? This is particularly hand if you’re only going to have one application in the screen session. If more, it would probably be better to have a more descriptive session name of some sort.

Sharing a screen

If someone else, or you, has created a screen, and would like to share with someone else what you’re doing, then screen -x does the trick. Simply use:

screen -x irc

..if irc is the name of the session, or the process ID. Once done, you should have enabled multi display mode. And if you find out that the screen you have taken part of doesn’t match up to the size of your own terminal, simply use:

Ctrl-a F (^a F)

..to force it to match up to the dimensions.

Multiple applications in one session

Now I’ve introduced you to the basics of using screen. Let’s proceed with using screen with multiple applications. Detach and resume the screen session called irc with:

screen -dr irc
nano

And the application will start. Let’s give this internal screen session a name. Press Ctrl-a Shift-a (a A). Notice that a is different from A (capital A).

You will be asked:

Set window's title to:

Type editor and press enter.

You can switch between the various applications by pressing Ctrl-a 0-9, so:

Ctrl-a 0

will go to the first application, irssi in this case. Other ways of navigating is by using

Ctrl-c Ctrl-n (next window)

Ctrl-c Ctrl-p (previous window)
Ctrl-a " (^a ")

You’ll get a list that looks something like:

Num Name                                                                   Flags

  0 irssi                                                                      $
  1 nano                                                                       $

Use your Up/Down arrows and press enter to select a shell to go to.

Clearing destroyed sessions

screen -wipe

Splitting windows

Ctrl-a Shift-s (^a S)
Ctrl-a TAB (^a TAB)

Now that you’re in the new area, there’s not much to do but to create another shell, so do it with:

Ctrl-a Ctrl-c (^a ^c)

From here you can start another application in the regular way, and give the internal shell a name of its own.

If you want to close the application in the bottom area, do it as normal, then to kill the area, press:

Ctrl-a Shift-x (^a X)

If you want to kill every area EXCEPT then one you’re currently in, you can use:

Ctrl-a Shift-q (^a Q)

And that’s pretty much it when it comes to screen. For more information, check out the command:

man screen

Good luck!

Vim – Commenting out multiple lines

There are two ways to do this without a vim plugin:

  1. Select your lines with VISUAL BLOCK (CTRL-V), then press I to insert before all highlighted lines. Next type your comment character (#, ;, depending on the language), then press ESC twice.
s/^/#

In other words, substitute the selected start of lines with the # character.

Select browser from variable DISPLAY

I have two monitors at work, which I like to use in a separate X-screen setup. Meaning that each monitor has an own X-server running on it. Thing is though, I like to use Firefox on Monitor 1, while I use Google Chrome on Monitor 2. So with this script, right-clicking a link in Monitor 1 will open it up in Firefox, while if I do so on Monitor 2, it will open it up in Google Chrome. Very nifty. Just go to System -> Preferences -> Preferred Applications (if you’re using GNOME like moi) and select this script instead of a regular browser.

#!/bin/bash
# A little script that selects a browser
# to show an URL on, based on the variable
# DISPLAY on a separate X-screen setup.
# In other words, the active monitor.
#
# Jorge Enrique Barrera 

if [ "$DISPLAY" = ":0.0" ]; then
    /usr/bin/firefox $1
elif [ "$DISPLAY" = ":0.1" ]; then
    /usr/bin/google-chrome $1
fi

Rapidshare Linux script revisited

Update: I just added a new variable in the script, DAYS, which specifies how many days the cookie you create is valid for.
Update 2011-09-13: Seems Rapidshare have been tampering with their API, which made the cookie-generating script useless. I basically changed the getaccountdetails_v1 with getaccountdetails, and the script is working fine now. I’ve fixed the script below to reflect this.

The code to get the Rapidshare-cookie in my previous post about this subject, Rapidshare Linux Script, unfortunately doesn’t work anymore. It seems that Rapidshare has moved from using https://ssl.rapidshare.com/premzone.html to https://ssl.rapidshare.com/cgi-bin/premiumzone.cgi, so things just don’t work as they used to. This is for people with a premium account.

However, there’s a solution. First off, log in to your Rapidshare-account, go to Settings and make sure to check the box named Direct downloads, requested files are saved without redirection via RapidShare.

To grab the cookie you need, place the piece of code below in a file, save it, do a chmod +x on it. Just remember to replace MyUserName and MyPassword with your username and password before you run the script:

Note: The script requires curl to be installed.

#!/bin/bash
# Script to get your Rapidshare-cookie, nom nom
# Jorge Enrique Barrera

# Variables you can change
USERNAME="MyUserName" # Username to your Rapidshare premium-account
PASSWORD="MyPassword" # Password
COOKIEJAR="/home/jorge/.cookies" # Where the cookies are to be placed
DAYS="30" # The number of days the cookie is valid for

## Do not change anything below here ##

DATA="sub=getaccountdetails&withcookie;=1&type;=prem&login;=$USERNAME&password;=$PASSWORD"
COOKIE_STRING=$(curl -s --data "$DATA" "https://api.rapidshare.com/cgi-bin/rsapi.cgi" | grep cookie | cut -c 8-)
COOKIE=".rapidshare.com TRUE / FALSE $(($(date +%s)+24*60*60*$DAYS)) enc $COOKIE_STRING"

if [ ! -d $COOKIEJAR ]; then
        echo "Creating the directory $COOKIEJAR."
        mkdir $COOKIEJAR
        echo "Done."
fi

echo "$COOKIE" | tr ' ' '\t' > $COOKIEJAR/rapidshare

Now that the cookie is present, you can proceed by downloading the files you want. Which way you do that, is up to you.

Either way I will paste two scripts, one with wget and the other one with aria2, and you can then make your pick. Just place the URL of the files you want to download in /home/YourUsername/Downloads/.url, one in each line:

wget

#!/bin/bash
LIST="/home/jorge/Downloads/.url"
cd ~/Downloads
for url in `cat $LIST`
do
    wget -c --load-cookies /home/jorge/.cookies/rapidshare $url
done

Save this file as wrsd.sh and make it executable by doing a:

chmod +x wrsd.sh

aria2

#!/bin/bash
cd ~/Downloads
aria2c -j 5 -c --load-cookies=/home/jorge/.cookies/rapidshare -i /home/jorge/Downloads/.url

Enjoy. :)

Python password generator

#!/usr/bin/env python
# Filename: passgen.py

import random, string

mystr = string.ascii_letters+string.digits
random_string = []

while len(random_string) <= 8:
    random_string.append(random.choice(mystr))
print "".join(random_string)

Acer Aspire One USB rescue image

A lot of people have been asking about where to find a rescue USB image for the Acer Aspire One. A long time ago someone with the nick gouki volunteered to host the file on a private server, but unfortunately, this is not so anymore.

I have placed the file on a new server, so you can now find it at http://jorge.fbarr.net/files/aa1_usb_recovery_image.gz. Right on the link and select Save link as to download it.

As for instructions on how to use it, I’ll repost a snippet of what I’ve written previously in the article Acer Aspire One Tips and Tricks: _ I had to use an external USB drive for this, as I don’t have a USB-pen that’s above 125MB, but it works just the same. Besides the Acer One Aspire, I’ve another machine with Fedora 9 on it. Once the external drive was plugged in, this is what dmesg came up with:

usb 2-2.1: New USB device found, idVendor=1058, idProduct=0702
usb 2-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
usb 2-2.1: Product: External HDD
usb 2-2.1: Manufacturer: Western Digital
usb-storage: device found at 14
usb-storage: waiting for device to settle before scanning
usb-storage: device scan complete
scsi 16:0:0:0: Direct-Access     WD       1200BEVExternal  1.02 PQ: 0 ANSI: 0
sd 16:0:0:0: [sdb] Write Protect is off
sd 16:0:0:0: [sdb] Mode Sense: 00 00 00 00
sd 16:0:0:0: [sdb] Assuming drive cache: write through
sd 16:0:0:0: [sdb] Write Protect is off
sd 16:0:0:0: [sdb] Mode Sense: 00 00 00 00
sd 16:0:0:0: [sdb] Assuming drive cache: write through
sdb: sdb1
sd 16:0:0:0: [sdb] Attached SCSI disk
sd 16:0:0:0: Attached scsi generic sg2 type 0

So now we know that the drive has been assigned /dev/sdb. Let’s make the recovery usb drive then.

zcat aa1_usb_recovery_image.gz > /dev/sdb

Notice that it’s /dev/sdb and NOT /dev/sdb1, as we’re overwriting the whole disk, and not just a partition of the disk.

That did the trick for me. Once the command was completed, remount the external drive and you’ll see that the new contents is there. Unmount it again, plug it into your Acer Aspire One, boot the machine, and press F12 during boot to select the USB-pen/external harddrive as the device to boot. You should be on your way towards recovery. :)

If someone happens to know how to do this in Windows, please give me a shout so that I can add it to this post. :)

A big thanks to Mithrandir for providing the file. :)

Spotify for Linux RPM

I’ve taken the liberty of converting the “Spotify for Linux”-files located at from .deb to .rpm. For now it can only be used if you have a Premium account.

To install it on Fedora 13, do the following:

su -
rpm --nodeps -Uvh http://jorge.fbarr.net/files/spotify-client-gnome-support.noarch.rpm http://jorge.fbarr.net/files/spotify-client-qt.i386.rpm

And that’s it. Now you can run Spotify as a Linux-application instead of through Wine. :)

This post never gets old. I constantly keep finding new and useful addons for Firefox. Here’s the list of what I consider to be some of the best Firefox addons out there.

  • Adblock Plus
  • Ever been annoyed by all those ads and banners on the internet that often take longer to download than everything else on the page? Install Adblock Plus now and get rid of them.
  • MediaplayerConnectivity
  • Allow you to launch embed video of website in an external application with a simple click.
  • StartupMaster
  • Asks for the master password at startup (fixes multiple password prompt).
  • Tab Mix Plus
  • Tab Mix Plus enhances Firefox’s tab browsing capabilities. It includes such features as duplicating tabs, controlling tab focus, tab clicking options, undo closed tabs and windows, plus much more. It also includes a full-featured session manager.
  • Tiny Menu
  • Replace the standard menu bar with a tiny menu popup.
  • Tree Style Tab
  • Show tabs like a tree.
  • Xmarks
  • Xmarks is the #1 bookmarking add-on. Install it on all your computers to keep your bookmarks and (optionally) passwords backed up and synchronized. Xmarks also helps you uncover the best of the web based on what millions of people are bookmarking.
  • It’s all Text!
  • Right click on a text area, select “It’s All Text!” and edit the text in the editor of your choice.
  • Web Developer
  • The Web Developer extension adds a menu and a toolbar with various web developer tools.
  • BarTab
  • BarTab can intercept when tabs are loaded in the background or restored after a browser restart and will only load the content when the tab is actually visited. It also allows you to free memory by unloading already loaded tabs, either manually or automatically.

Nginx, PHP, MySQL and WordPress continued

So, my machine at home took the plunge. A couple of days ago while I was reorganising the livingroom (I was not bored, I actually love doing that stuff), I placed the server on the floor, as it usually was placed above the TV. Michael then decided to play a little ON/OFF-game with the server. The powersupply was fried, and I can’t really bother to buy a new one at this moment. So, it was finally time for me to buy a VPS from out there somewhere. My decision fell on , and they actually seem pretty good so far, so now to see if it will last.

My concern was though, VPS’ (Virtual Private Server) aren’t usually that good, they have limited diskspace and hardware. I don’t need much of diskspace, but after some experience with Apache, I know it’s a huge memory-hog. So what I basically needed was Apache, MySQL, PHP and WordPress. I didn’t think it was going to work out, until a nice co-worker of mine tipped me off about nginx.

This was supposedly a very good, and very lightweight webserver, according to him. So I decided to give it a shot. And so far, it’s working wonders.

Here I’ll try to explain how to set up your server with nginx, MySQL, PHP and WordPress.

FastCGI

FastCGI is what your webserver uses to interact with PHP-code, and this is not something that comes packaged with nginx.

There are two options you can use, and I have tested both. spawn-fcgi or php-fpm. I ended up using php-fpm, though spawn-fcgi is quicker to set up. I’ll try to explain how to set up both.

spawn-fcgi

spawn-fcgi, which came with the webserver lighttpd. You usually had to download lighttpd first, compile it, and then grab the program from there. But for your convenience, you can get the spawn-fcgi here, or just go to , and grab the source there to compile on your own (seems to be an own project now).

So basically, as root, do the following:

wget http://jorge.fbarr.net/files/spawn-fcgi
mv spawn-fcgi /usr/local/bin

Now, the next step is to make this program run at boot. For those of you using a RedHat’ish type of system, adding this to the end of /etc/rc.d/rc.local will do the trick. You can add it by running this command:

echo '/usr/local/bin/spawn-fcgi -f /usr/bin/php-cgi -a 127.0.0.1 -p 9000 -P /var/run/fastcgi-php.pid -u nginx -g nginx' >> /etc/rc.d/rc.local

php-cgi is the name of the fcgi-application, which is usually provided by your distribution’s PHP-package (I believe it’s php-common for CentOS/Fedora, so make sure you have it installed), and is referred to by the -f in the command. -a makes you specify which address to listen on, -p is the port (9000 in this case), and -P is the file to place the process ID in when the program is started, which makes it easier to kill the program if necessary.

Once placed in the rc.local-file, just run it manually to fire it up:

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

php-fpm

php-fpm is a patch for php4/5 to greatly improve FastCGI SAPI usage in production. This means that you don’t install php through your distribution’s package manager, but rather download the package from the PHP-website, and the patch from another site. You patch up the sourcecode, compile things, and get it started.

One of the dependencies for how we’re going to compile PHP is MySQL, so install that first by typing:

yum install mysql mysql-devel

Then get the PHP-sourcecode by typing:

cd /usr/local/src
wget http://no2.php.net/get/php-5.3.0.tar.bz2/from/no.php.net/mirror

And the patch itself:

wget http://php-fpm.org/downloads/php-5.3.0-fpm-0.5.12.diff.gz

Then execute the following command:

tar -jxvf php-5.3.0.tar.bz2

Now we patch the newly downloaded PHP:

gzip -cd php-5.3.0-fpm-0.5.12.diff.gz | patch -d php-5.3.0 -p1

And enter the new directory to start compiling things:

cd php-5.3.0/
./configure --enable-fpm --with-mcrypt --enable-mbstring --with-mysql=/usr/include/mysql --with-mysql-sock=/tmp/mysql.sock --with-curl --enable-sockets --with-gd --with-zlib --with-iconv --with-jpeg-dir=/usr/lib

Notice: If you are using a 64-bit system you have to add in an –with-libdir=64 for it to compile correctly. According to Raja Varma you need to use –with-libdir=lib64 for it to compile properly in a CentOS 64 bit installation. Thanks for the tip Raja!

At this point the compile failed quite a bit, as I had to install several more packages. The packages I had to install were the following (a snippet taken from yum.log):

Apr 23 08:34:44 Installed: zlib-devel-1.2.3-3.i386
Apr 23 08:34:50 Installed: libxml2-devel-2.6.26-2.1.2.7.i386
Apr 23 08:37:10 Installed: keyutils-libs-devel-1.2-1.el5.i386
Apr 23 08:37:18 Installed: libsepol-devel-1.15.2-1.el5.i386
Apr 23 08:37:23 Installed: libselinux-devel-1.33.4-5.1.el5.i386
Apr 23 08:37:30 Installed: e2fsprogs-devel-1.39-20.el5.i386
Apr 23 08:37:35 Installed: libidn-devel-0.6.5-1.1.i386
Apr 23 08:37:40 Installed: krb5-devel-1.6.1-31.el5_3.3.i386
Apr 23 08:37:46 Installed: openssl-devel-0.9.8e-7.el5.i386
Apr 23 08:38:07 Installed: curl-devel-7.15.5-2.1.el5_3.4.i386
Apr 23 08:40:15 Installed: libjpeg-devel-6b-37.i386
Apr 23 08:41:54 Installed: 2:libpng-devel-1.2.10-7.1.el5_3.2.i386
Apr 23 08:43:38 Installed: libmcrypt-2.5.8-4.el5.centos.i386
Apr 23 08:44:37 Installed: libmcrypt-devel-2.5.8-4.el5.centos.i386

Once everything compiles successfully, we continue with:

make all
make install

Now that everything is ready to go, we only need to modify two lines in the file /usr/local/etc/php-fpm.conf. Simply replace nobody with nginx, and remove the comments, making the lines look like this:

            Unix user of processes
            nginx               

            Unix group of processes
            nginx

And that should be it. Fire up php-fpm with:

/usr/local/bin/php-cgi --fpm

Making an init-script for php-fpm is pretty easy – simply make a symlink that points to /usr/local/php/sbin/php-fpm:

cd /etc/rc.d/init.d
ln -s /usr/local/sbin/php-fpm php-fpm

Now add the following line to /etc/rc.d/rc.local to make php-fpm start up at boot:

/usr/local/sbin/php-fpm

And you’re done!

Now to the next item on the list, nginx.

nginx

nginx (pronounced as “engine X”) is a lightweight, high performance web server/reverse proxy and e-mail (IMAP/POP3) proxy HTTP server and mail proxy server written by Igor Sysoev.

So based on that we’re using CentOS now, we are going to get the necessary package from the EPEL-repository. Run these commands to fetch the package, and to install it:

wget http://download.fedora.redhat.com/pub/epel/testing/5/i386/nginx-0.6.38-1.el5.i386.rpm
yum --nogpgcheck localinstall nginx-0.6.38-1.el5.i386.rpm

Once installed, we need to configure three files, mainly. /etc/nginx/fastcgi_params, /etc/nginx/nginx.conf and /etc/nginx/conf.d/virtual.conf (if you want to have several virtual domains). The first file, fastcgi_params, we just need to add a little something. Open up the file and add the following line to it, right under SCRIPT_NAME:

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

Save and close the file.

This is what my nginx.conf pretty much looks like:

Notice: According to :

…do not use the given nginx,conf, it is malicious point your server to his site.

Let me just say again, this is what MY configuration file looks like. I’ve simply pasted it so that you can see how a working configuration looks. So if you want it to work for you, you need to modify the values to suit your setup. I thought that was needless to say, but guess not. :)

#######################################################################
#
# This is the main Nginx configuration file.  
#
# More information about the configuration options is available on 
#   * the English wiki - http://wiki.codemongers.com/Main
#   * the Russian documentation - http://sysoev.ru/nginx/
#
#######################################################################

#----------------------------------------------------------------------
# Main Module - directives that cover basic functionality
#
#   http://wiki.codemongers.com/NginxMainModule
#
#----------------------------------------------------------------------

user              nginx;
worker_processes  1;

error_log         /var/log/nginx/error.log;
#error_log        /var/log/nginx/error.log  notice;
#error_log        /var/log/nginx/error.log  info;

pid               /var/run/nginx.pid;

#----------------------------------------------------------------------
# Events Module 
#
#   http://wiki.codemongers.com/NginxEventsModule
#
#----------------------------------------------------------------------

events {
    worker_connections  1024;
}

#----------------------------------------------------------------------
# HTTP Core Module
#
#   http://wiki.codemongers.com/NginxHttpCoreModule 
#
#----------------------------------------------------------------------

http {
    include       /etc/nginx/mime.types;
    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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    proxy_read_timeout 300;

    #gzip  on;

    # Load config files from the /etc/nginx/conf.d directory
    include /etc/nginx/conf.d/*.conf;

    #
    # The default server
    #
    server {
        listen       80;
        server_name  chihiro.fbarr.net;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }

        error_page  404              /404.html;
        location = /404.html {
            root   /usr/share/nginx/html;
        }

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:20080
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    include        fastcgi_params;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
}

The only thing I’ve changed here is server_name, which I’ve set to chihiro.fbarr.net. This is like the main server we’re working with. Now I’m going to want to set up the virtual host jorge.fbarr.net on this machine as well. For that we need to configure the file /etc/nginx/conf.d/virtual.conf. This is what mine looks like:

#
# A virtual host using mix of IP-, name-, and port-based configuration
#

## jorge.fbarr.net
server {
    listen       80;
    server_name  jorge.fbarr.net;

    port_in_redirect off;

    root   /var/www/jorge.fbarr.net;

    proxy_redirect     off;
    proxy_redirect     http://jorge.fbarr.net:80/  /;

    access_log /var/log/nginx/jorge.fbarr.net-access.log;
    error_log  /var/log/nginx/jorge.fbarr.net-error.log;

    include /etc/nginx/fastcgi_params;

    index   index.php;

    if (!-e $request_filename) {
        rewrite ^(.+)$ /index.php?q=$1 last;
    }

    location ~ .*\.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
    }
}

## jorge.ulver.no redirect

server {
    listen      80;
    server_name jorge.ulver.no;

    rewrite ^(.*) http://jorge.fbarr.net$1 permanent;
}

That’s pretty much it. Everything should be working just fine by now. :) But we are lacking two things, MySQL and WordPress.

MySQL and WordPress

To install MySQL, type up the following:

yum install mysql-server

As for how to set up MySQL, if you follow these instructions, it will tell you how you need to set up your database to work with WordPress, so I won’t be posting details about that here.

For PHP to be able to work with MySQL (if you have chosen to use spawn-fcgi and not php-fpm), you need to install a package called php-mysql. Install the package with yum, kill php-cgi, and start it again by doing these following things:

yum install php-mysql
pgrep php-cgi | xargs kill
/usr/bin/spawn-fcgi -f /usr/bin/php-cgi -a 127.0.0.1 -p 9000 -P /var/run/fastcgi-php.pid -u nginx -g nginx

Once everything is done, voila! You should now have nginx, PHP, MySQL and WordPress working together. And as you probably notice, nginx is taking a LOT less resources than Apache would have.

Issues with PHP

If you notice that errors such as the following are popping up on your site:

It is not safe to rely on the system’s
timezone settings. Please use the date.timezone setting, the TZ
environment variable or the date_default_timezone_set() function.

You can do the following:

cp /usr/local/src/php-5.3.0/php.ini-production /usr/local/lib/

Then open up the file php.ini and change:

;date.timezone =

to

date.timezone = "Europe/Oslo"

If you happen to live in Oslo. Change it to whatever is right for you really. Also, find the line that says something like:

error_reporting = E_ALL & ~E_NOTICE

And change it to:

error_reporting = E_ALL & ~E_DEPRECATED

Restart php-fpm and nginx and things should be back to normal.