Posts Tagged ‘apache’

How To Install Apache, MySQL and PHP (WAMP) On Windows Manually

Friday, May 29th, 2009

If you are using Windows as your operating system when developing your websites you should always test your websites on your local system before you upload the files to your live server.

Although there are several pre-packaged Apache-PHP-MySQL (WAMP) packages available for download when using these you are bound to their release cycles and the structure of the directories they are using.

This article describes how you can install Apache, PHP and MySQL manually on your local system with maximum flexibility because you can quickly update one program if the need may arise, e.g. if a new PHP version has been released.

This method also shows you where specific files are located which you may need to edit when changing settings so you can dive a bit deeper into the configuration files which may be quite helpful if an error occurs.

WAMP Setup

In this tutorial I’m assuming the following:

  • Apache, PHP and MySQL are installed to subdirectories of d:\webserver
  • The document root is d:\webroot
  • the first test domain is www.webserver.local
  • the document root for that VirtualHost is d:\webroot\www.webserver.local\htdocs which will contain all documents accessible via the browser

Installing The Apache Server

First of all you need to download the latest Windows distribution of the Apache HTTP server from the Apache download page. Pick the MSI installer including OpenSSL which is named something like „Win32 Binary including OpenSSL 0.x.x (MSI Installer)” and is listed under the section named something like “Apache HTTP Server 2.2.xx is the best available version”.

After launching the setup program pick the „Custom” setup and choose the directory d:\webserver\Apache as the installation path. Enter the information as shown in the screenshots below.

apache-install

apache-install-2

Installing PHP

Dowload the latest (stable) PHP 5 version from the PHP download page. Choose the „PHP 5.x installer”. After download and launching the file when prompted to select a directory choose d:\webserver\PHP

php-install

Webserver Setup – “Select the Web Server You Wish To Set Up” select “Apache 2.2.x”.

php-install-2

When prompted for the Apache configuration directory select d:\webserver\Apache\conf.

php-install-3

On “Choose Items To Install” select the extensions you’d like to install.

If you don’t know which might be useful you may use the following list to find some suggestions:

  • cURL (good for accessing HTTP servers)
  • EXIF (if you’re dealing with photos and wish to extract meta information)
  • GD2 (image creation and manipulation)
  • Multi-Byte String (mbstring, for i18n, e.g. conversion from ISO-8859-1 to UTF-8)
  • mcrypt (for encryption)
  • mysql, mysqli
  • other database extensions you might be using (postgreSQL etc.)
  • OpenSSL (for accessing https URLs)
  • PDO, PDO_Mysql, PDO_SQLITE
  • SOAP (if you’re planning to access SOAP resources or create you own SOAP server)
  • SQLite

Installing MySQL

To download the MySQL server visit this MySQL website and download the Windows MSI Installer package under „Community Edition”.

To ease administration and creation and editing of tables and databases I encourage you to download and install the MySQL GUI tools as well.

In the MySQL setup dialog pick the custom installation and select the directory d:\webserver\MySQL as the installation directory.

mysql-install-1

mysql-install-2

When configuring the MySQL server use the detailed configuration.

mysql-install-3

Use “Developer Machine” as your server type

mysql-install-4

Select “Multifunctional Database” in the database usage dialog:

mysql-install-5

Keep the default InnoDB tablespace settings and click Next:

mysql-install-6

Select “Decision Support” on the next dialog:

mysql-install-7

Keep the default values on the next screen:

mysql-install-8

When prompted to select a character set use the one that fits best, I’m using UTF-8 as the default charset.

mysql-install-9

On the next dialog you have to choose whether to install the server as a Windows service and if it shall be started automatically at boot time. This setting depends on how often you’re developing on your system. I’m keeping MySQL running in the background most of the time because it doesn’t eat that much memory.

mysql-install-10

The next dialog prompts you to select a root password. Keep this in mind.

mysql-install-11

After the installation has finished the MySQL server is already running and you can now begin to configure PHP and Apache.

Configuring Your System

For every VirtualHost (i.e. website/domain) you need to add a corresponding entry to your HOSTS file so that your browser knows that the given domain will be handled by the webserver running on your local system. Edit the file c:\windows\system32\drivers\etc\hosts with a text editor.

Windows Vista Information

On Windows Vista you have to launch Notepad as an administrator to see and edit the file.

Add a new line to your hosts file which has the following content:

1
127.0.0.1 www.webserver.local

Now requests to www.webserver.local from your browser will be sent to the webserver running on your local system.

Configuring The Apache Webserver

There are actually two files to edit. Please note that you always need to use forward slashes or a double backslash in path names.

General Settings

Open the file d:\webserver\Apache\conf\httpd.conf and search for the line reading

1
DocumentRoot "D:/webserver/Apache/htdocs"

The default document root is D:/webserver/Apache/htdocs. We now need to change this to point to the d:\webroot directory as defined above. So change this line now to

1
DocumentRoot "d:/webroot"

You also need to modify the line reading

1
<Directory "D:/webserver/Apache/htdocs">

to

1
<Directory "D:/webroot">

If you wish to use .htaccess files you also have to change the line reading

1
AllowOverride None

to

1
AllowOverride All

To include the VirtualHosts file which will contain all mappings of hostname to document root directory (and more) you have to change the line

1
#Include conf/extra/httpd-vhosts.conf

to

1
Include conf/extra/httpd-vhosts.conf

To enable automatic execution of an index.php file when the user accesses a directory (which you should always do) you need to add index.php to the DirectoryIndex directive just as in this example – simply add „index.php” to the end of the line:

1
2
3
4
5
<IfModule dir_module>

DirectoryIndex index.html index.php

</IfModule>

Creating The VirtualHosts Configuration

Open the file d:\webserver\Apache\conf\extra\httpd-vhosts.conf. Now it’s time to create a VirtualHost for our domain www.webserver.local.

Just add the following block to the end of the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
<VirtualHost *:80>

ServerAdmin webmaster@example.com

DocumentRoot "D:/webroot/www.webserver.local/htdocs"

ServerName www.webserver.local

ErrorLog "logs/webserver.local-error.log"

CustomLog "logs/webserver.local-access.log" common

</VirtualHost>

This will tell Apache…

  • that the server administrator can be reached via webmaster@example.com (no need to enter your real email address, because on your own development system you’re the only one that would see your real email address so it doesn’t make sense
  • that the documents for www.webserver.local can be found in the directory d:/webroot/www.webserver.local
  • to log errors to the file d:/webserver/Apache/logs/webserver.local-error.log
  • to log every access to d:/webserver/Apache/logs/webserver.local-access.log

Creating The Documents

Create the directory D:/webroot/www.webserver.local/htdocs recursively and create the file D:/webroot/www.webserver.local/htdocs/index.php with the following contents:

1
<?php phpinfo(); ?>

Configuring PHP

The default PHP installation would not show you any errors in the browser and instead just return a 500 server error which would materialize as an empty white page.

Although this is the recommended setting for productions servers where you do not normally want to reveal any specific information like paths when an error occurs this makes life quite hard on your local development server. To enable the display of error messages in the browser open your php.ini file which is located at d:\webserver\php\php.ini and change the line

1
display_errors = Off

to

1
display_errors = On

To enable sending of emails via the mail() function you need to define a specific SMTP server name and port. You would normally enter your providers’s mail server name here. Please keep in mind that some providers use a so-called „POP-Before-SMTP” so that sending mails with PHP may fail if you have not downloaded new messages via POP3 from the server before.

Testing The Installation

Now you are ready to test your new web server. First of all you need to restart the Apache server via the included taskbar tool or via the Windows services panel.

After that open up your browser and enter http://www.webserver.local/

This should show the phpinfo() page.

And now: have fun developing!

How To Create Search Engine Friendly RewriteRules For Domains

Tuesday, May 19th, 2009

Do you have multiple domains pointing to your website? From an SEO standpoint you shouldn’t have them all pointing to your document root directory because this might be interpreted as duplicate content by the search engines or you might even get a mixup of pages distributed over several domains and subdomains (like example.com and www.example.com) in the organic search results.

If you are using Apache and have access to the RewriteModule you should configure the VirtualHost like this so that all domains and subdomains are redirected to the main hostname via a search engine friendly HTTP 301 redirect:

<VirtualHost *:80>
ServerAdmin webmaster@example.com
DocumentRoot /srv/www/example.com/htdocs
ServerName www.example.com
ServerAlias example.com
ServerAlias www.example.org
ServerAlias example.org
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule (.*) http://www.example.com$1 [L,R=301]
…
</VirtualHost>

This will redirect all requests not going directly to http://www.example.com to that hostname. So even if someone enters http://example.org/index.php the server will issue a redirect to http://www.example.com/index.php.

Of course this also works if someone links to your page with a link like http://example.com/file.gif. In that case the redirect will be issued to http://www.example.com/file.gif. Google likes that.

tweetthis-15

How To Achieve Maximum Website Performance (Part 5)

Tuesday, May 12th, 2009

Welcome to the fifth part of this article series on how to maximize the performance of your website. The focus of this article is mostly on compressing content on the way from the server to the user’s browser.


6. Compress That Code

All modern browsers support the compression of content transferred via HTTP and indicate this by sending the appropriate Accept-Encoding header just like this:

Accept-Encoding: gzip,deflate

This header tells the server that the browser supports compression of content using either the GZIP algorithm or the deflate algorithm.

To optimize your site and speed up the load time you should add compression to the output your server is sending. If you are using Apache (which I have always assumed throughout this article series) it works as described as follows.

Just like you installed the ExpiresModule as described in part 4 you can install the DeflateModule (“mod_deflate”) in your Apache web server by adding this line to your httpd.conf file:

LoadModule deflate_module       modules/mod_deflate.so

Most of the time it does not make sense to compress images or packed files because they have already been compressed so I suggest you focus on the HTML code. You can achieve this by adding this block to either your httpd.conf file or to any VirtualHost you wish to use the compression for.

<IfModule deflate_module>
AddOutputFilterByType DEFLATE text/html
</IfModule>

Just by adding this configuration to the VirtualHost for this domain (saschakimmel.com) at the time of writing the data transferred for this blog’s homepage was reduced from almost 170 KB to only 27 KB – that’s a reduction of 84%!

I highly recommend using this Apache module as it reduces the traffic enormously.

If you just wish to use output compression in your PHP scripts you can simply use this code:

<?php
ob_start("ob_gzhandler");
?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>

This will tell the PHP interpreter to use output buffering, i.e. to buffer all of the output of the script until it has finished when it will call the ob_gzhandler from PHP. This handler detects if the browser supports compression at all and will only send the code as compressed data if it does.

7. Using YSlow

If you have read each of the articles in this series you pretty much know every possible performance optimization for a website so now let’s have a look at the analysis of the YSlow addon for Firefox. If you have not already installed this addon you should install it now.

After installing it and restarting your Firefox browser type the URL of the page you wish to optimize into the address bar and hit the enter key. If the page has finished loading you need to open the YSlow tool by clicking on the icon in the browser’s status bar.

yslow

If you click on the button labeled “Run Test” it takes some seconds during which YSlow reloads and analyzes the page. This will show you a list of recommendations like the one below.

yslowresult

If you have read all parts of this series you should by now already have optimized most of the things you can optimize on your website. Please note that YSlow only shows you what you can optimize, not what you already have optimized. It won’t show me that the main page is already delivered with compression it only shows me which files are not yet compressed on this blog so keep this in mind when reading the recommendations.

8. Outsourcing Your Data To A CDN

If you get lots of traffic (and I am talking about really lots of traffic here) to static files like images, videos and downloads you should think about hosting your files on a content delivery network.

You just upload the data to their network and modify the links on your website pointing to these files. You have to pay a fee depending on the amount of data served to your users through these networks. If you already know that your server is not likely to be able to handle all of that traffic you might have a closer look at these services.

The most prominent ones are Amazon Simple Storage Service (S3) and MOSSO.

9. Adding Cache Headers For The WordPress Sociable Plugin

As I just had a look at the YSlow recommendations for my blog I found out that I could add expiration headers for these graphics so I just added this info here because I think it may be quite helpful for you.

Just add this code to your VirtualHost which belongs to your WordPress blog:

<LocationMatch /wp-content/plugins/sociable/images/*>
        ExpiresActive On
        ExpiresDefault "access plus 7 days"
</LocationMatch>

Please note that you need to have the ExpiresModule installed on your server for this to work as described in part 4 of this series.

This concludes this article series. Download your free Website Performance Checklist now.

tweetthis-15

How To Achieve Maximum Website Performance (Part 4)

Monday, May 11th, 2009

Welcome to the fourth part of the article series on how to maximize the performance of your website. This time I will show you how you can minimize the number of HTTP requests to your server by setting appropriate cache headers so that the browser does not request the file time and again while a visitor is browsing your site.

5. Caching And Expiration

Most of the people think that if a browser has downloaded a file like an image or CSS file from the server it has stored it in the cache directory on the local harddisk and will retrieve it from there without sending a new request to the server every time it is embedded in an HTML page.

However this is simply not true. Modern browsers just like Firefox or Internet Explorer 7 will most of the time send an “If-Modified-Since” request to the server to find out if the file has been updated on the server. This is good because your browser can use the file from the cache if it has not changed on the server without downloading the file again.

Well, this still is an HTTP request that is sent to your server. Just think about how often you change images, CSS and JavaScript files on your server. Every 2 minutes?

Most of the time your answer to that question will simply be “No.” although this makes sense for some specific files like images from a webcam that may be updated every few seconds.

Cache Headers

This is the HTTP response header sent to your browser when you access this blog:

Live HTTP Headers Addon For Firefox showing headers

Live HTTP Headers Addon For Firefox showing headers (German version)

Let’s examine the different headers in detail:

Expires: Wed, 11 Jan 1984 05:00:00 GMT

This tells your browser that the file has already expired so that the browser should retrieve from the server again next time it is requested.

Cache-Control: no-cache, must-revalidate, max-age=0
Pragma: no-cache

These headers tell the browser that it must not cache the file and always has to revalidate if the file on the server has been updated.

Last-Modified: Sun, 10 May 2009 18:06:04 GMT

When looking at the headers of static files like images you will often see a header like this which is the file modification time.

Time To Optimize

So now let’s optimize the header settings for some of our files. This optimization assumes that you are using the Apache web server. If you do not have root level access to your web server you cannot use this optimization as described here, regretfully. There are other ways which I am planning to write about in a later post.

First of all you need access to your webserver configuration. You need to add the Expires module (“mod_expires”) to your Apache configuration file httpd.conf like this where all the other lines beginning with LoadModule are located at the beginning of the file:

LoadModule expires_module       modules/mod_expires.so

This will load the Expires module into your Apache web server. Now you need to add the following lines to your VirtualHost configuration – the VirtualHost given is only an example – just add the <IfModule>…</OfModule> block  to your existing VirtualHost block for the domain you wish to speed up.

<VirtualHost 127.0.0.1:80>
ServerName      example.com
DocumentRoot    /srv/www/example.com/htdocs
CustomLog       /logs/example.com.access_log combined

<IfModule expires_module>
	<Location /flvplayer.swf>
	      ExpiresActive On
	      ExpiresDefault "access plus 1 day"
	</Location>

	<Location /img>
       	ExpiresActive On
	      ExpiresDefault "access plus 2 hours"
	</Location>
</IfModule>

</VirtualHost>

This example code assumes that you want all of the files in the /img directory to be cached on the client side for two hours and the file /flvplayer.swf to be cached for one day. You can add as many <Location> blocks as you wish. There are several options available you can look up on the Apache website.

By using this method Apache will add the appropriate HTTP headers automatically.

Setting Manual Headers In Your PHP Files

You can also set expiration and caching headers automatically in your PHP files. By default as PHP is a language where the code is interpreted at runtime PHP sends an Expires header with a date long gone. Here is some example code:

1
2
3
4
5
6
7
$cacheTime = 60*60; // 1 hour

header("Expires: " . gmdate("D, d M Y H:i:s", gmmktime() + $cacheTime)." GMT");

header("Pragma: public"); // HTTP/1.0

header("Cache-Control: public, max-age=".(int)$cacheTime.""); // HTTP/1.1
WARNING!

Never set the last two headers if the page you are using it on contains user-specific data. This means: if you offer a login on your homepage don’t add the last two lines as this may result in proxies between your server and the visitor’s PC storing this data so that another person who is using the same proxy might see confidential data belonging to the other user – “public” says it all in the code above. In all other cases you can normally safely  use the code as shown above. Just modify the cache time to suit your needs.

How To Find The Perfect Cache Time Value

You should resist the temptation to set the expiration for all of your files to one day or anything more than a few hours. Just imagine you have an image on your website which shows a product with the price next to it. If you change the price when the user returns to your website several hours later (which may depend on your business) he will not be able to see the updated price because the original file has not yet expired in his browser’s cache.

I suggest using several different values depending on how often specific content changes. Your company logo for example is unlikely to change every day (unless you are Google, of course) so you may set a high value here. Just remember that you can (OK, should be able to) change the value on your server at any time so if you are planning to update some images you may as well lower the value a few days or hours before the change is scheduled to happen.

There is no rule of thumb so you just have to think about the different types of files and how often you update these files.

This concludes this article. I appreciate your comments below – feel free to retweet!

Read the next part.

tweetthis-15