Chapter  27

Lion as a Web Server

Lion makes doing everything with the Web as easy as doing it on Mac OS X. We talked about surfing the Web with Safari in Chapter 9 and about generating content for the Web throughout the book. There's one thing left to do: become part of the Web itself by hosting a web server.

To some that might sound complicated, but it doesn't have to be. Getting started is as easy as clicking a button. For the hardcore Net geeks, don't be fooled by Mac OS X's cuddly appearance. When you want to get fierce, there are fangs and claws to go around.

So, whether you'd like to host a home page for your neighborhood bridge club, build an intranet for your home or office, or develop and stage web applications for production and profit, keep reading. In this chapter, we will do the following:

  • Introduce the Apache web server
  • Start basic web sharing in Mac OS X
  • Serve our own web page from Mac OS X
  • Delve into advanced Apache configurations
  • Introduce PHP
  • Introduce SQLite, MySQL, and PostgreSQL
  • Cover some other important details for hosting your own web site from your Mac

Apache and Mac OS X Web Sharing

Mac OS X's built-in web server is the Apache HTTP server, a web server which traces it's linieage back to the NCSA HTTPd server, one of the first web servers ever written. Today the Apache HTTP Server (often reffered to as just Apache) is the most popular web server currently used today (in May 2011 it was estimated that approximately 63% of all website were run using Apache). For Mac OS X users, this means that they can easily replicate most web servers on thier Mac for development purposes and then seemlesly deploy thier finished web sites and web applications to larger servers. Of course it's not unheard of for websites to be hosted directly from a Mac.

Apache's current incarnation, Apache 2, stands ready to host your personal home page right from you own computer, as shown in Figure 27–1.

Image

Figure 27–1. Mac OS X's default personal home page shown in Safari

To enable all this goodness, you need to turn on web sharing in the Sharing preference pane in System Preferences. Select the Web Sharing box, and you may imagine your computer shuddering slightly as Apache rumbles to life. Once the check box is tamed, the dialog helpfully explains where everything is, as shown in Figure 27–2.

Image

Figure 27–2. Activating web sharing from System Preferences

NOTE: If your site doesn't show up, see the “Tips and Tricks” section later in this chapter.

CAUTION: Turning on web sharing is an all-or-nothing proposition. If you turn web sharing on for one account, it will be on for all accounts. To change this behavior, see the “Configuring Apache” section later in this chapter.

Customizing Your Site

As the information panel in the Sharing preferences explains, your personal home page is kept in your user Sites directory. The items in your Sites directory are what will be served when you visit the personal web site link. For example, using a text editor or your choice (you can use Mac OS X's built-in TextEdit app, but make sure you select Format > Make Plain Text from the menu if you choose to) and type in the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>A very simple web page</title>
</head>
<body>
    <h1>My new personal home page</h1>
    <p>By learning a little HTML, or using your web development tool of choice, you can
easily build and serve your own website right from your Mac OS X computer!</p>
</body>
</html>

Then save the file as index.html in your ~/Sites directory (it's okay to replace the default index.html file). Then reload your personal web site, and you should see a new, very simple web page (Figure 27–3).

Image

Figure 27–3. A customized personal home page shown in Safari

NOTE: The web page example in Figure 27–3 is about a simple as you can get with Hypertext Markup Language (HTML), the original and most prominent language of the Web. Combined with Cascading Style Sheets (CSS) to format your content, you can build some very nice-looking web pages. Teaching HTML and CSS goes beyond the scope of this book, but there are numerous books and online resources that can get you started. Learning at least the basics of HTML and CSS (if not continuing on to JavaScript, PHP, and other web development languages) is a very useful and highly recommended endeavor.

NOTE: For creating HTML pages, I strongly recommend a decent plain-text editor (not TextEdit). There are many to choose from; however, for getting started, you can't go wrong with Bare Bones' TextWrangler, which is both free and easily available from the Mac App Store. As you progress in web development, you may want to look into more advanced text editors such as TextWrangler's big brother, BBEdit, or look into full-featured web development tools such as Coda or Espresso.

NOTE: For creating HTML pages, I strongly recommend a decent plain-text editor (not TextEdit).

TIP: Don't forget that you have access to both Vim and Emacsfrom the command line, either of which make excellent editors for web development.

In addition to the user sites located at ~/Sites, your machine also has a main system site, as shown in Figure 27–4. This site's content is located in the Apache server's document root. Unlike the logical ~/Sites location, the default document root is /Library/WebServer/Documents/. On a single-user machine, these two sites can be combined, as discussed in the “Tips and Tricks” section later in this chapter.

Image

Figure 27–4. If everything is working right with your web server, visiting http://localhost/ will let you know.

ACCESSING YOUR COMPUTER'S WEB SITE

Customizing Apache

Since Apache is a Unix application, it doesn't have a convenient GUI preference pane, and it doesn't use a standard Macintosh property list. Rather, it has its own configuration file in its own directory using its own peculiar scheme.

NOTE: Actually, there are third-party applications that provide a GUI to Apache's configuration file; however, none of them really simplifies the process too much, and there are some obscure important details. As such, we won't cover any of these and generally don't recommend them. Additionally, Mac OS X Server provides its own very nice GUI for Apple's web server.

Fortunately, the configuration file, like everything else about Apache, is well documented and, honestly, not that complicated. Links to the Apache manual, as well as a dire warning instruction you should read and understand, is at the top of the httpd.conf configuration file. To begin, you should keep the link to the Apache documentation home page handy: http://httpd.apache.org/docs/.

By default Apache's configuration files live in the /etc/apache2 directory, which in Mac OS X is actually located in /private/etc/apache2 (though /etc/apache2 will work). Unless you've turned on the ability to see invisible files in the Finder, you'll have to navigate there in Terminal. Listing the contents of the directory shows the primary file we've come here to see: httpd.conf.

NOTE: Although it's called Apache, the name of the Unix executable is httpd, which reflects its role as a background process (daemon) that serves the Hypertext Transfer Protocol.

Open httpd.conf in your text editor of choice. Again, TextWrangler or BBEdit are excellent for this. With BBEdit, you can use its disk browser to easily navigate here, since it can see the hidden folders. It will also take care of overwriting the old file, which is read-only. You can also use Nano, Emacs, or Vim, as detailed in Chapter 23.

NOTE: In Lion all the Apache configuration files are protected as unwritable. Before you make any changes to a conf file, you must chmod it so it can be written to. Otherwise, you will be unable to save any changes. The easiest way to do this is from the command line by issuing this: sudo chmod u+w httpd.conf. When you are done editing the file, you should reverse the process with sudo chmod u-w httpd.conf. The chmod command was covered in Chapter 23.

The configuration file is very long, but don't be scared. Lines that start with the number sign are comments, which is to say they are ignored. The file mainly consists of hints explaining what the various sections do. There's very little actual content here, and even less you have to worry about. We will work through the file and describe the essential sections as they appear.

NOTE: Prior to Apache2, the httpd.conf file was generally a single self-contained file that contained all the configuration options in one place. With Apache2, it became customary to break out certain configuration options into other files that are then pulled into httpd.conf when the file is read. As we encounter areas where information is stored in separate files, I will let you know.

ServerRoot

Much as Unix considers ~ to be a shortcut for your user directory, the ServerRoot command tells Apache where it should look for any files that are not explicitly named. Since these files are all for its internal use, there's really no need to change the default value.

Listen

Like any server process, Apache listens on a particular port or socket. Normally, it answers any incoming calls on port 80. If you need to change the port for some reason or you want to bind to a specific IP address, you can edit this.

One particular use for Listen is to limit who can see your page. Remember how we said you could load your page by one of several means? What if you don't want people to be able to load your page elsewhere on the network? By binding Apache to 127.0.0.1:80, you will be able to view the page locally only. Dialing in to the actual IP address would simply return an error page.

Another use for the Listen directive is to use a port other than the default. For example, your ISP may block access to port 80 in an effort to prevent you from running a web server from your home. You could instead bind to port 8080.

You can bind to multiple ports and sockets by issuing multiple Listen directives. So, for example, to view the site locally on the standard port but to let others see it only on a secret port, you could say this:

Listen 127.0.0.1:80 Listen 1984

You could then load your site by simply pointing to 127.0.0.1, but someone else on the network loading your site would get an error unless they knew to append the correct port to the end of your IP address. So, for example, if your IP address were 10.0.0.1, they would have to point their browser to http://10.0.0.1:1984.

Dynamic Shared Object (DSO) Support

Dynamic Shared Object (DSO) is a fancy name for the LoadModule directive. As the name may suggest, LoadModule loads . . . modules, which are plug-in software products that extend the functionality of Apache. Several modules are loaded by default. We will come back to LoadModule when we are ready to add PHP to our web server.

NOTE: You may notice here sections that are wrapped in tags such as <IfDefine MACOSXSERVER></IfDefine>. If the IfDefine directive is met, then the commands within the tags are run; otherwise, they are ignored. Here you may notice that one set of commands is run for Mac OS X Server (<IfDefine MACOSXSERVER>) while another is run if the system is not Mac OS X Server (<IfDefine !MACOSXSERVER>). Later we will see the similar IfModule used in a similar manner depending on whether a specific module is loaded.

User/Group

Since Apache operates on your system, it needs to be able to access files. You could run it as root, but that would be a security risk. Instead, Apache runs as the user _www as part of the group _www. Should you want to change this, you would do that here. Honestly, though, you probably don't need to do that.

VirtualHost

If you have a web site running on a host somewhere, chances are you're not on a dedicated server. Lucky for everyone involved, you can run multiple sites on a single machine using a feature called virtual hosting.

Virtual hosting is off by default, but if you want to configure multiple sites to run on your machine, perhaps because you work on multiple sites and would like to access them all separately, you can do so.

Incidentally, the different user sites built into Mac OS X, while similar to virtual hosting, are actually a different feature; they're user directories, provided by Apple's UserDir module. User directories are for multiple users on one site, while virtual hosts are for multiple sites on one machine.

ServerAdmin

One of the nice things Apache does is automatically generate index and error pages for you. Since these pages may require action by the server administrator, they will include an e-mail address. That address is given with the ServerAdmin directive.

ServerName

Similarly, the ServerName directive is how the server refers to itself. This would typically be the domain name and port, or possibly the IP address. Since this information can be determined automatically, it's commented out by default. Should you find yourself actually serving web pages to the public, you should define it explicitly.

DocumentRoot

This directive tells Apache where to start serving pages from. That is to say, it defines which directory on the host machine is represented by / in the web address. Directories attached to / will be similarly mapped to directories on the host machine.

By default, the document root is set to /Library/WebServer/Documents, so loading http://127.0.0.1/ loads the contents of/Library/WebServer/Documents. Loading http://127.0.0.1/Site/Welcome.html loads the file /Library/WebServer/Documents/Site/Welcome.html (if such a file exists).

If you wanted to change the document root to your user directory, you could change the DocumentRoot directive to the following:

DocumentRoot  "/Users/username/Sites"

You can also redirect the document root using symbolic links, as discussed in the “Tips and Tricks” section later in this chapter.

Permissions

There's no actual Permissions directive, but that's the best term we can think of to describe the several entries that follow. These define the options for directories and files on the system. A notable entry is the Options FollowSymLinks directive, which is on by default and which allows our symbolic link trick to work.

There are several more entries that block web visitors from being able to see certain types of files, such as hidden files that begin with a dot or the Mac OS X resource files.

One thing to keep in mind is that there are permissions entries for every known directory, including the document root. If you change a directory elsewhere in the configuration, you will have to be sure to change its permissions entry as well. This is one of the reasons why using symbolic links is easier than editing the configuration file.

DirectoryIndex

Easily missed amid all the permissions directives, the DirectoryIndex directive defines the default index file name. That is to say, when a user simply points to a directory, which file do they get? The default is index.html, which is why you don't have to type index.html all the time when you're surfing the Web.

If you decide to start using PHP or some other technology that requires you to use a different file name or extension, you can edit this. By including multiple listings, you can give several possible defaults. Apache will serve up the first one it finds. For example, to serve index.html by default but then serve the old Microsoft FrontPage standard, welcome.html, as a backup, you would say the following:

DirectoryIndex index.html welcome.html

If nothing listed in DirectoryIndex exists, visitors will see a listing of everything in the directory. To prevent that, you can put a failsafe at the end of the DirectoryIndex directive, such as a reference to a file in your root directory telling people to stop poking around in your directories:

Directorylndex index.html welcome.html /lost.html

NOTE: It's actually possible (and more common) to remove the ability to present an index of everything located in the directory without the reference file; you just remove the indexes from the directory options earlier in the configuration file.

Logging

Several directives are related to logging. You can customize where logs are kept, how much logging Apache should do, and what format log messages are in. These are best kept to the default values, but if you spend a lot of time reading your logs and you develop an opinion on some aspect of logging, here is where you can flex your will.

Redirects

Much like the DocumentRoot directive, the Redirect, Alias, and ScriptAlias directives let you map the URLs people request to your file system.

Redirect will actually cause the browser to request a new location. This is useful if you've permanently moved a file to elsewhere on the system. Alias will cause a given path to look outside the normal document root hierarchy.

For example, you might want to give the outside world access to your Pictures directory (for some reason) by mapping requests to www.yoursite.com/pictures to /Users/username/Pictures. You could, of course, also accomplish this with symbolic links, assuming you allow FollowSymLinks on the directory.

ScriptAlias is like Alias, but it applies specifically to directories that contain executable scripts, rather than simple documents.

DefaultType

Most of the Internet uses MIME types to determine how it should deal with files. Since most web servers serve web pages, it's appropriate to leave this set to the default, text/plain.

NOTE: MIME stands for Multipurpose Internet Mail Extensions. Like most of the Internet, it has been expanded beyond its original purpose.

What makes this directive interesting is actually the list of AddType and AddHandler directives, which allow you to add support for certain types of files. The list starts with a TypesConfig directive that points to an external list of types, stored by default in /private/etc/apache2/mime.types.

Most webmasters meet the types section when adding PHP support, because the traditional .php file extension is not handled by default; however, on Mac OS X this is handled for you in the PHP configuration file (/private/etc/apache2/other/php5.conf).

ErrorDocument

If you ever go poking around the coolest sites on the Net, they always seem to have these sexy custom error pages, so pulling a 403: Access Denied doesn't jar you from the overall design of the site. The ErrorDocument directive lets you point to custom pages and scripts.

If you define a custom error document, be sure to actually implement it, lest your users not only be treated to a generic error page but also be blighted with the ever-embarrassing “Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.”

Include

Apache configuration is typically split into multiple files. External files are referred to using the Include directive. For the purposes of scope, you can consider the entire text of an included file to be inserted where the Include directive is used.

This is important, because the general rule with Apache is that the last word is the one that's obeyed. So, if an included file disagrees with the main file, the one farther down the list is going to win. If you find some configuration detail is not working, despite being clearly documented, make sure you're not being overridden by another file.

Of particular importance is this line:

Include /private/etc/apache2/extra/httpd-userdir.conf

Editing the httpd-userdir.conf file reveals two things. First, it uses the UserDir directive to tell Apache that every user's personal root is their Sites directory. If, for example, you are old-school and you'd prefer this directory to be called publichtml, this is where you'd set that up.

Second, this file in turn includes all conf files contained in the directory /private/etc/ apache2/users. Listing that directory reveals a series of files of the form username. conf, where username is a username on the system.

Each of these files contains a permissions directive.

<Directory "/Users/username/Sites/">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all </Directory>

Again, username refers to the actual username dealt with by the file.

By default, all directories on your system are forbidden, except for those explicitly named. This directive makes the named user's Sites folder readable and sets up a few options. Were this file to be missing, you would not be able to access your site, regardless of system-level permissions.

When you turn on web sharing, these files are created by default. By editing the files, you can disallow certain users the ability to host sites. You could even remove the main include, disabling all user sites, while giving yourself the document root.

NOTE: Although disabling the explicit permissions on a user directory will do the job in a roundabout way, the proper way to enable or disable users is with the UserDir directive. See the Apache documents for more information.

Activating Changes to the Apache's Configuration

Whenever you change Apache's configuration file, you will need to restart Apache. The easiest way to do this is with Terminal, using the special Apache control program, apachectl.

sudo apachectl graceful

This will restart Apache gracefully, which is to say it will let it finish what it's doing, shut down, and then restart.

If you try to restart Apache but it's not already running for some reason, it will just start. If you've messed up the configuration file, it will usually let you know on restart. Otherwise, you should be ready to test your changes.

PHP

PHP is the weapon of choice for many developers for creating dynamic web pages and applications. PHP is a dynamic scripting language that can be embedded in web pages. PHP is processed by the server, outputting normal HTML. Unlike client-side technologies such as JavaScript, PHP developers know their scripts will run with the capabilities they need.

Since it is open source, PHP is the preprocessor of choice on Unix systems running Apache. Indeed, PHP has been implemented as an Apache module and comes installed, but not activated, by default on Mac OS X.

To properly ensure PHP is installed, you need to have a PHP page. The best test page is a simple PHP Info page. It relies on PHP to be working, so it's a good test, and it gives you a lot of information about your PHP installation, so it's actually useful.

Create a PHP Info page in your favorite text editor, and save it to your document root as index.php. All you need to include is a single call to PHP's built-in phpinfo function:

<?php phpinfo() ?>

Then, load the page in your browser of choice by pointing to http://localhost/index.php. You have to point to the page explicitly, because otherwise you'll get the default index page, index.html.

NOTE: You can, of course, also save the PHP Info page to your home Sites directory.

Loading the page in your browser, you're greeted with the entirety of its source, as written. That's because Apache doesn't know what a .php file is, so it's serving it as its default MIME type, text/plain.

To enable PHP, you simply need to uncomment a single line of text from the Apache configuration file:

#LoadModule php5_module                 libexec/apache2/libphp5.so

Since it starts with #, it's a comment and is ignored. Delete the # and save. Back in the day, you'd also have to tell Apache how to handle the file type and look for index.php by default, but all that stuff is now handled automatically by the included php5.conffile. Just restart Apache, and, as the saying goes, there is no step 3. The PHP Info screen should now display properly, as shown in Figure 27–5.

Image

Figure 27–5. PHP Info page provides the details about the version of PHP installed on your computer.

Examining the PHP Info page will tell you a lot about how your server is set up. It's a good idea to run it on both your local machine and your remote host so you can be aware of any differences between versions, features, or configuration options that might affect you.

To learn more about PHP, including an extensive manual with installation and integration guides, visit PHP's official web site at php.net.

NOTE: PHP certainly isn't the only game in town for server-side web development on your Mac. All the common open source web scripting languages are there including Perl, Python, and Ruby, and newer web frameworks are generally easily available. For example, installing Ruby on Rails is a simple sudo gem install rails away.

Databases

Many web servers add a database server to the operating system, web server daemon, and scripting engine. You can add several databases to Mac OS X, Apache, and PHP. Choosing a database is a balance between power and effort. Mac OS X has a database server running and ready, but if you need more features than the default setup provides, it's going to take some doing.

SQLite

Mac OS X's default database manager is the fast, simple, lightweight SQLite that is quickly gaining popularity with web developers. It's compatible with the same Structured Query Language (SQL) used by nearly every other database in the world. More important, it's directly addressable from PHP.

Aside from the fact that SQLite is already set up for you, it has the major advantage of being the same database server used throughout the system. Applications written with CoreData can use SQLite as their backing store. That means you can share a database between your Core Data application and your PHP web site without ever having to touch SQL.

Note: FormoreinformationonCoreDataandotherapplicationdevelopmenttopics, see Chapter33.

If you're serving web pages from your machine or if your remote host has SQLite (and the requisite PHP modules) running, you're good to go. Run sqlite3 from the command line to access the included management program. You can also learn more by visiting http://sqlite.org/.

MySQL

When it debuted in 1995, MySQL was the scrappy alternative to the Tyrannosaur-like Oracle. What it lacked in features and polish, it made up for by being fast and small. It helped that it was free, open source software, quickly establishing itself next to Linux, Apache, and PHP in the standard LAMP (Linux, Apache, MySQL, and PHP) stack, which is one of the more popular setups for web hosting these days.

As time went on, MySQL added features to better compete with the name-brand databases. This meant giving up its spot as everyone's favorite nimble, lightweight database to SQLite. If, however, you want to be like everyone else and run MySQL, you're going to have to install it yourself. Fortunately, MySQL maintains a Mac OS X installer package on its web site, http://dev.mysql.com. To install MySQL, simply download the disk image that matches your architecture and run it.

Although it's available in more traditional tarball format, I downloaded the more Mac-like disk image installer package. This contains an installer for the database server itself and a separate installer if you'd like MySQL to start automatically. If you're running a web server, that's probably a good idea.

Once it's installed, you can start the MySQL server from the command line. It's installed in /usr/local/mysql, which is not in the default path, so to run any MySQL tools you will have to actually go into the directory or use the full path:

sudo -b /usr/local/mysql/bin/mysqld_safe

TIP: If you included these lines into your .bash_profile as shown in Chapter 23:

if [ -d /usr/local/mysql/bin ]; then
    PATH=/usr/local/mysql/bin:"${PATH}"
fi

then you can omit the /usr/local/mysql/bin/ part since that should already be in your $PATH.

After entering your password, the server will start. The -b flag on sudo invokes the server as a background process. You can eliminate the background flag on your first run just to make sure everything is copacetic.

Alternately, if you installed the startup item, you can use it to start the MySQL database:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM start

Finally, the installer includes a MySQL preference pane for System Preferences, as shown in Figure 27–6. Double-clicking the MySQL.prefPane will install it after asking you whether to install it just for you or for all users. The preference pane tells you whether MySQL is running, lets you start and stop MySQL, and includes a setting to automatically start MySQL at boot time.

Image

Figure 27–6. The MySQL pane in System Preferences

By default, MySQL sets up a root user with full access and no password. In other words, until you do something about it, your MySQL installation is completely unsecured. The first thing to do after starting the server is to lock down that root account. The easiest way to do this is with the MySQL command-line admin tool:

/usr/local/mysql/bin/mysqladmin -u root password "newpwd"

where newpwd is your new password.

NOTE: Aside from the root user, there are also two anonymous accounts with unsecured root access. However, these accounts can access only those databases whose names start with test_, and only from the localhost, so they are not much of a risk. Still, if you are actually planning on serving pages professionally, you should lock or remove these accounts. See the online MySQL manual for more details.

Once it's installed, the default MySQL client program can be invoked from the command line, like so:

/usr/local/mysql/bin/mysql -u root -p

The -p flag will cause MySQL to prompt you for your password. Once you enter it, the command-line client program will launch. Type help to get a list of available commands, and type quit to exit.

GETTING PHP AND MYSQL TO PLAY NICE IN MAC OS X

PHP and MySQL are expected to run together, so once you have MySQL running, PHP will notice immediately. Reloading your PHP Info page will confirm this. Beyond that, accessing MySQL in PHP, setting up user accounts in MySQL, and the sometimes maddening/sometimes magical world of database programming are beyond the scope of this book. Fortunately, there is no end of online resources, and there are several excellent books, including Beginning PHP and MySQLby W. Jason Gilmore (Apress, 2010), PHP and MySQL Web Developmentby Luke Welling and Laura Thomson (Addison-Wesley, 2008), and MySQLby Paul DuBois (Addison-Wesley, 2008).

PostgreSQL

While SQLite concentrates on pure performance and MySQL maintains a good mix of performance and added support for advanced features, PostgreSQL has always been conceived as an enterprise-level solution. It has more advanced capabilities (e.g., multiple indexing algorithms) and can be hooked up to the enterprise directory and authentication servers, LDAP, and Kerberos, but it is still free, open source software.

For more information on PostgreSQL, visit its official home page at www.postgresql.org where you can get information for downloading and installing the latest version on Mac OS X.

NOTE: PostgreSQL is actually installed by default on Mac OS X Lion Server, and some PostgreSQL client tools are accessible from the Client command line. Despite the existence of pieces of PostgreSQL on the Client version of Lion, PostgreSQL isn't there; however, it certainly will run well once installed.

Tips and Tricks

The joy of running a web server on a personal computer is in mucking around with things. Sometimes a little hackery makes things more convenient; other times, it's just good, clean fun, like mixing chemicals together to see what happens. If that seems to imply a little tingle of danger, so be it. Make of these what you will.

Making Sites the Document Root

If you're developing web content, you want your local server setup to mirror your remote setup as closely as possible. Since ~username sites went out of fashion with Geocities, that means working out of the document root. Compared to the user Sites directory, working out of/Library/WebServer/Documents seems so un-Mac-like.

If you're the only user on your machine, you can unify your Sites directory (or a root-level Sites directory you'd create) with Apache's document root. There are a couple of ways to do this.

The Unix way is to edit Apache's configuration file, as discussed in the earlier “Configuring Apache” section. The nice thing about setting the document root in httpd.conf is that it's portable. As long as you use the same username, your configuration file will work on any machine. It also doesn't rely on file system trickery, which makes it seem more pure.

The Mac way is to replace the file that the configuration file points to with a symbolic link. This uses the file system to fool Apache into loading a site different than it expects. This is the same method Mac OS X uses to bridge the Finder's view of things to the Unix beneath.

Creating a symbolic link leaves the configuration file untouched, which makes it that much harder to mess up, but at the end of the day, it really doesn't matter which one you use.

NOTE: A symbolic link is similar to an alias on Mac or a shortcut on Windows. In Mac OS X, links are Unix file system constructs, while aliases belong to the Finder. Using an alias to redirect your document root will not work.

To redirect your document root using symbolic links, navigate to the /Library/WebServer directory. Move aside the original Documents folder. You could delete it, but simply renaming it to something like OldDocuments will do the trick.

Launch the Terminal application and invoke the following command:

sudo ln -s ~/Sites /Library/WebServer/Documents

This means, “Using superuser privileges (sudo), create a link (ln) that is symbolic (-s) from my local Sites directory (~/Sites) to the path/Library/WebServer/Documents.” If your user account does not have administrator privileges, you can invoke your admin user via the -u flag, as follows:

sudo -u yourAdminUserName ln -s ~/Sites /Library/WebServer/Documents

Since you're using sudo, this will prompt you for your password. After entering it, invoking ls on/Library/WebServer will show a file called Documents. In the Finder, it will appear to be a shortcut. Loading the root site in your browser of choice should show your personal home site.

TIP: Your browser may have the old page cached, so you might need to reload or even empty your cache to see the change.

Troubleshooting Permissions

On a clean installation of Mac OS X, getting your home page to load really is as simple as selecting a check box, but if you've been lugging the same home directory around since 10.0, things can get a little weird. The same is true of site contents. A new site should have no problems, but importing an old site from who-knows-where might leave things broken.

One of the most common problems is seeing a 403 Forbidden message instead of a page on your site. This is caused by having improper permissions settings on Sites or its contents. In general, folders serving web sites need to be readable and executable by everyone, while web documents and files should be readable by everyone.

You can check and fix permissions on your Sites folder and its content using the Finder's Info panel by selecting the folder or file and pressing Command-I. You can also use the chmod command from the Terminal.

Domain Name Tricks

Were you so inclined, you could set up a DNS server, but why? Chances are your registrar has a name server, so providing you have a static outside IP address, you can simply have them point to it and start welcoming visitors to your self-hosted web site.

However, not everyone has the need to spend the money on a static IP address, especially when you consider that the cost of getting one is greater than the cost of professional web hosting. If you're setting up a web host just because it's fun, because you want to save money, or because you're doing local development, paying for a static IP address is overkill.

Custom Domains Without DNS

You can actually override DNS at a local level. Mac OS X maintains a list of known hosts in a file called /private/etc/hosts. Editing this file will let you map web addresses to IP addresses. Why would you do this?

First, looking at IP addresses all day is boring. That's why DNS was invented, after all. It's much more fun to give your local network machines fun names at imaginary top-level domains. Then you can surf over to http://i.am.awesome.

Second, if you are developing web pages locally, you might run into a problem with absolute paths. That is to say, if you have a link pointing to www.mydomain.com/somefile.php, your browser will want to go to the remote version, rather than the local version you're developing.

The hosts file is the first place your machine looks when it tries to resolve a domain. Rerouting calls to mydomain.com or www.mydomain.com to your local machine is easy. Just open /private/etc/hosts in your favorite text editor, and then add the following line:

127.0.0.1 mydomain.comwww.mydomain.com

Just remember to edit the hosts file back to normal before trying to surf the Web, or strange things might happen. On the other hand, maybe you want strange things to happen. One technique for blocking web content from unwanted domains is to route them to a blank page. Here's an example:

128.0.0.1 doubleclick.com

For more information on the hosts file, invoke man hosts in Terminal.

CAUTION: It's OK to add things to the hosts file, but don't edit any of the existing entries. The system has that stuff there for a reason.

Dynamic DNS

If you've configured port mapping to reach your machine from the Internet but don't want to spend the money on a static IP address, you can use a dynamic DNS service to keep your domain name pointed to the right place.

There are many cheap to free services, such as No-IP (www.no-ip.com) and FreeDNS (http://freedns.afraid.org/), that will let you point a domain name to your dynamic IP address. Unlike a standard name server, dynamic DNS services keep a very short refresh time on their name servers, so changes propagate quickly.

Other Considerations

Here are a couple more things worth checking out:

  • Mac OS X Server: If you're running a site as a hobby or as a small business, the standard version of Mac OS X is all you need, but Apple does produce a server version of Mac OS X, aimed at the enterprise. It has some additional administrative features that, while available in Unix form, have been wrapped in that great Mac OS X user experience. If you're using Mac OS X as a server, you might look into it. Visit www.apple.com/server/macosx/ for more details.
  • Ruby on Rails: Although PHP is a popular way to create web applications, it's far from the only game in town. One platform that's rising fast is Ruby on Rails. Ruby is an object-oriented programming language, not unlike PHP 5. Rails is a development framework written in and for Ruby.

Summary

With its open source and Unix roots, Mac OS X is built from the same stuff as the Internet itself. It's no wonder the Mac is such a great platform for web development. Whether you're serving web pages to the public right from your desktop or just building a development environment on your laptop, Mac OS X comes with everything you need, and adding more is easier than ever.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset