Unix System Administration » Web Servers

ID #1010

How to install a server with lighttpd, PHP 5 and MySQL 5 on FreeBSD?

With the advent of light-weight server-side software and agile web applications, more and more people are using lighttpd as their web server because it uses very few resources. Let's see how to install a complete developer environment on a FreeBSD or PC-BSD system. To begin with, I assume you have your ports up-to-date. Let's start installing lighttpd.

Installing lighttpd

Open your terminal and issue:

$ su -
# cd /usr/ports/www/lighttpd
# make install clean

And compile lighttpd with MySQL support when prompted. Now, let's create a directory to put our .php and .html files, and change the owner to you (change charles to your username):

# mkdir -p /usr/local/www/data
# chown -R charles:charles /usr/local/www/data
# ln -s /usr/local/www/data ~charles/Desktop/www

We'll create a PHP test file:

# vi /usr/local/www/data/index.php

Now, let's put the following content to our index.php file:

<? phpinfo(); ?>

And save. Let's also allow read/write of log files (if they don't exist yet, create these files) so that lighttpd doesn't complain:

# chown www:www /var/log/lighttpd.access.log
# chown www:www /var/log/lighttpd.error.log

Now, let's configure lighttpd.conf:

# vi /usr/local/etc/lighttpd.conf

You will need to:

  • Uncomment mod_fastcgi under server.modules
  • Make sure server.document-root is set to /usr/local/www/data
  • Make sure server.event-handler is set to freebsd-kqueue and is uncommented
  • Make sure server.port is either commented or set to a common port such as 80
  • Make sure server.username and server.groupname are both defined as www
  • Uncomment the whole fastcgi.server section and set the full path to php-cgi such as:
fastcgi.server             = ( ".php" =>
( "localhost" =>
"socket" => "/tmp/php-fastcgi.socket",
"bin-path" => "/usr/local/bin/php-cgi"

When you're done, save your file. If, for some reason, you erased or corrupted your file, download a copy here. On FreeBSD, lighttpd doesn't know explicitely where his configuration file is, so what we're going to do is create a wrapper to launch lighttpd and to pass automatically the configuration file as a parameter, launching lighttpd will be easier as well, and we will make the file executable:

# vi /usr/bin/lighttpd
/usr/local/sbin/lighttpd -f /usr/local/etc/lighttpd.conf $@
# chmod +x /usr/bin/lighttpd

Save. Optionally, if you would like lighttpd to start together with FreeBSD during bootup, issue the following command:

# echo 'lighttpd_enable="YES"' >> /etc/rc.conf

You have the following options to control lighttpd: start, stop, and restart. Now, let's start lighttpd:

# lighttpd start

That's it for lighttpd. Let's install PHP with the PHP extensions.

Installing PHP

A common use of PHP on Apache is mod_php which is fast, as Apache loads the module into memory when starting. With lighttpd, you will use PHP-CGI with FastCGI to have the same speed and performance. FastCGI basically uses cache, which make PHP-CGI a lot faster than regular CGI (hence the name "FastCGI"!). Let's install PHP 5 with FastCGI support. Open your terminal and issue:

# cd /usr/ports/lang/php5
# make install clean

During compilation, you will be ask to choose and to check several options. Make sure FastCGI is selected. After PHP is installed, let's see if FastCGI support is here:

# /usr/local/bin/php-cgi -v
PHP 5.1.6 (cgi-fcgi) (built: Sep 17 2006 23:27:28)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies

It should read cgi-fcgi somewhere in the description as seen above. Let's install the PHP Extensions now and select the extensions you need for your development such as GD, PDF, etc:

# cd /usr/ports/lang/php5-extensions
# make config
# make install clean

Now that you are done installing lighttpd and PHP with FastCGI support, open http://localhost/ to see our phpinfo() page. It should work! The last application we need is MySQL server and client, which is pretty straight-forward.

Installing MySQL

We'll now install MySQL from the ports. Just issue:

# cd /usr/ports/databases/mysql51-server
# make install clean

The full path to MySQL server is too long, let's make it shorter. We'll create a shortcut:

# cd /usr/local/bin
# vi mysql-server
/usr/local/etc/rc.d/mysql-server start $@

Save your file. The MySQL server also has 3 options: start, restart, stop. To start the MySQL server, you will do:

# mysql-server start

If you want the MySQL server to start each time FreeBSD is booted, issue the following command:

# echo 'mysql_enable="YES"' >> rc.conf

To use MySQL through the terminal, just issue:

# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 5.1.6-alpha
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

To exit, type exit. Here's a few more information that will help you to get started quickly:

To create the MySQL root password, you will do:

# mysqladmin -u root password my_password_here

To log into MySQL:

# mysql -u root -p  

To create a new database:

# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 5.1.6-alpha
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> create database name_of_my_database_here

To grant permissions to a user over a particular database:

# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 5.1.6-alpha
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> grant usage on name_of_my_database_here.* to name_of_user_here@localhost;

This is it! If you try to install a popular PHP script such as phpBB, it should work just fine:

To learn more about MySQL, feel free to read the excellent documentation. Now you should have a full development environment on a strong and robust operating system with state of the art open-source applications.

Tags: -

Related entries:

Last update: 2008-09-01 06:07
Author: Charles A. Landemaine
Revision: 1.2

Change language

Digg it! Print this record Send to a friend Show this as PDF file
Propose a translation for Propose a translation for
Please rate this entry:

Average rating: 3.7 out of 5 (23 Votes )

completely useless 1 2 3 4 5 most valuable

You cannot comment on this entry

Comment of Luke L:
two errors I saw in your otherwise flawless and very, very helpful How-To. Both in the mysql install section. First, when you are adding the mysql_enable command to rc.conf, you don't have the correct command. it reads: # echo 'mysql_enable="YES"' >> rc.conf while it should read: # echo 'mysql_enable="YES"' >> /etc/rc.conf Second, you have to chmod +x /usr/local/bin/mysql-server for it to work on boot. Again, the rest was very helpful. I like FLMP.
Added at: 2007-02-05 01:57

Comment of YouMustKnow:
Господа! Если вы интересуетесь немного политикой, то должны были заметить - эти неожиданные волнения в странах Африки возникли неспроста. Есть 2 версии этих событий - "официальная" и "неофициальная", и обе версии скорее уводят в сторону от реальных фактов. [b]Версия 1:[/b] Каддафи - тиран и самодержец, стрелял в мирных граждан, поэтому его надо бы убрать. [b]Версия 2:[/b] на самом деле Европе с Америкой захотелось немного Ливийской нефти, и они решили навести небольшой "дебош" Рассмотрим версию 1. Да, Каддафи уже тот ещё старик, ему конечно пора бы и на пенсию. Но известно ли вам, что конкретно в Ливии народ имеет весьма высокие преференции при его правлении? Учителя получают под $3.000, выплаты безработным порядка $1000 и так далее. Да, он стал укрощать группки взбунтовавшихся бедуинов, но кто-нибудь понимает реальные причины этих бунтов? Эта версия не выдерживает никакой критики. Версия 2. Нефть Ливии? Да, она отличается высоким качеством, Ливийская нефть очень чистая. Но её там не так много. Да и к тому же, зачем тогда будоражить Египет и прочие африканские государства, которые весь прошлый год вообще никого не тревожили и не волновали?! А тут вдруг - "тираны", "изверги" и т.п. Да, эта ситуация дополнительно подогрела цены на нефть. Отдельным корпорациям это выгодно. Но истина короче. Каддафи не так давно начал объединять ближневосточные страны под идеей перейти на расчёт за нефть и товары НЕ долларами, НЕ евро, а альтернативой всему этому. И Египет - одна из стран, которая это поддержала... Подробнее - здесь: http://sterligov.livejournal.com/4389.html Однако в популярных СМИ это никогда не скажут. P.S. У Саддама Хусейна, кстати, тоже были такие начинания. Вообще, после кризиса ооочень многие страны стали задумываться об ИЗБАВЛЕНИИ ОТ ЗАВИСИМОСТИ ОТ ДОЛЛАРА. Рано или поздно это произойдёт. ФРС уже некуда понижать ставки. Распространите это где сможете. Люди должны знать правду. Кстати, это тоже по теме: Великобритания примет участие в военной операции в Ливии, США, Франция перенесла вторжение в Ливию на сутки, операцию, Великобритания отчиталась об уничтожении ливийских ВВС, позициям, Россия отказалась участвовать в военной операции в Ливии, Лондон
Added at: 2011-04-25 00:24

Comment of nwUxmbSbkWwcQwlS:
Hey, that post leaves me felenig foolish. Kudos to you!
Added at: 2011-05-23 07:43

Comment of nAMdjvfWZaHNeDDs:
tUwG4b inxeuznedshw
Added at: 2011-05-24 05:10

Comment of eeSnOgFTwzZwLZYeHDG:
cAqH7L , [url=http://cfncobexntma.com/]cfncobexntma[/url], [link=http://aswkjakrnrbf.com/]aswkjakrnrbf[/link], http://hwxuvbyirwll.com/
Added at: 2011-05-24 12:06

Comment of xeRtZPPhPuehITeMTAf:
89RhMp natvadrtjxjm
Added at: 2011-05-28 04:32

Comment of LZQtZOkfkJ:
Z2wECY , [url=http://gemehrjaguxr.com/]gemehrjaguxr[/url], [link=http://ijdiyphwsnky.com/]ijdiyphwsnky[/link], http://jjqrxxnlgwco.com/
Added at: 2011-05-31 08:51

Comment of ozWxWlBybcyWWbr:
If you're reading this, you're all set, pradenr!
Added at: 2012-10-26 18:03

Comment of LikgcHKvL:
x6xLIo ybsniabrtjuf
Added at: 2012-10-27 02:58

Comment of JXoLBMsLvSrCrW:
A79GoZ ixqxscdururh
Added at: 2012-10-28 18:17

Comment of aQfyhFfNYnNL:
Jgq5N4 , [url=http://ajzrmxoqvfwu.com/]ajzrmxoqvfwu[/url], [link=http://schpobgcwdka.com/]schpobgcwdka[/link], http://wsbipwmkukxi.com/
Added at: 2012-10-28 23:00

Comment of 4nU3MMgRD:
 ( 2012.12.20 05:13 ) : 感谢博主,前几次借助博主的分享成功卸载了几次,但是反复多卸载重装个几次,不管用了,卸载不干净。后来用这个搞定了如果运行这些第二步、apt-get roveme mysql-server purge第三步、apt-get roveme mysql-common purge 您没卸载干净,那你可以 第一步、apt-get -f autoremove 第二步、apt-get roveme mysql-server purge 第三步、apt-get roveme mysql-common purge
Added at: 2013-11-16 05:35

Comment of mQTLkWDr3r7:
with the number_format that i used i have just found that if i go over a31000.00 it mseses the cart total up which is strange so i have gone to the money_format which sorts it all outthe only thing that was a small thing is displaying the a3 symbol for the british money it didnt like it so i leave it in the code as it was and then used this to display the money setlocale(LC_MONETARY, en_GB ); $pricetotal = money_format( %!10.2n , $pricetotal); note the ! it hides the symbols http://sdtefhz.com [url=http://rgoacwhmttv.com]rgoacwhmttv[/url] [link=http://qvahrurtpz.com]qvahrurtpz[/link]
Added at: 2013-11-17 17:29