phpBB front-end optimization – 1 hour workshop

July 13th, 2007. Tagged: CSS, performance, php, phpBB

Let's go ahead and optimize our phpBB installation for front-end performance. I'll follow Yahoo's 14 optimization rules, but only implement the ones that apply for phpBB. During this short workshop there will be no changes to the phpBB code, we'll create a new template instead, so that in case something bad happens, your board will continue to work normally. As an example, I'll use the bgcanada.com/phpBB2, the board I volunteer to administrate.

The plan

1. creating two subdomains to host assets - images and css, maximizing parallel downloads (also following rule #9)
2. creating a new template (theme) based on the default subSilver template
3. moving CSS to an external file (rule #8), merging the two css files (rule #1)
4. copying images and css to the new subdomains
5. making sure css is served gzipped (rule #4) and also making sure php pages are served gzipped)
6. turning ETags off (rule #13)
7. setting the Expires header (rule #3)
There will be no explanations on the reasoning why these rules exists, but only how to implement the applicable ones in phpBB. It's a good idea though to go through the links above and read the detailed description of the rules. Maybe you'll find something that can be done in addition to the plan above. The suggested implementations were done and tested on a normal $60/year shared host, working around the limitations of such hosting. I'll speculate that at least 90% of the phpBB installations out there use shared host so I hope my implementation will be relevant to your phpBB install as well.

New subdomains

Typically, shared hosts allow subdomains and have their admin interface for doing so. In case your host is an exception, alternatively you can buy one or two extra domains to use for the same purpose - storing page assets.

So in my case, for the domain bgcanada.com I create two sub-domains - i1.bgcanada.com and i2.bgcanada.com (i as in image). Now the question would be how to divide assets between the two domains. I decided that more or less half of the images are multilingual (they don't contain text) so these go to i2. i1 will have all the rest - translatable images found in subSilver/images/lang_english, smilies and the stylesheet.

creating a new template

Let's go ahead and create a new template (theme), based on the default subSilver template. I'll call mine "sso" as in "subSilver optimized" (or the longer mirror-like version "ssoss" as in "stoyan stefanov, oh, so smart" ;) )

For this purpose, just take the contents of path/to/phpbb/templates/subSilver and copy it under the name "sso", so you'll have /templates/sso, an exact subSilver copy.

Now go ahead and modify templates/sso/subSilver.cfg, the theme configuration. First rename it to sso.cfg. Then at the top of the document, replace the line:

$current_template_images = $current_template_path . "/images";

with

//$current_template_images = $current_template_path . "/images";
$i1 = "http://i1.bgcanada.com/sso"; // language and smilies
$i2 = "http://i2.bgcanada.com/sso"; // the rest

use your domain, of course.

Then do a search/replace. All occurrences of:

$current_template_images/{LANG}/

should become

$i1/{LANG}/

And all occurrences of

$current_template_images/

become

$i2/

At the end of the file, just before ?> add a new line:

$board_config['smilies_path'] = 'http://i1.bgcanada.com/smilies';

This will overwrite the path to the smilies you set in the admin interface. This is optional, you can achieve the same by using the admin panel, but we said we wanted to have the board unaffected by the changes.

Now open templates/sso/theme_info.cfg and replace all occurrences of "subSilver" with "sso".

Now the bad news is that some of the template files (.tpl) still contain relative paths to images, we need to make these absolute and pointing to the subdomians. Since these paths are hardcoded in the templates we're sure that they are language independent, so they'll all go to the i2 subdomain. If you have a good text editor that can search/replace in multiple files, go ahead. Alternatively, use the php script I came up with. Download it, copy it to your /templates/sso folder, rename to replace.php and use it like:
C:\path\to\phpbb\templates\sso> php replace.php
It will report what it replaced.
It only searches for templates/subSilver/images and replaces with http://i2.bgcanada.com/sso

Yep, almost done with the template, one last step - the css.

Moving CSS to an external file, merging

In the default subSilver there are style definitions in overall_header.tpl. Remove them, the whole thing between the <style> tags and replace with:

<link rel="stylesheet" href="http://i1.bgcanada.com/sso.css" type="text/css">

Now rename subSilver.css to sso.css. Copy the contents of formIE.css and append it to the end of sso.css. Optionally, you can walk through the new file and strip all comments and white space. Or use my stripped version.

Note that as a side effect, the font of the board will look somewhat different, because the definitions in subSilver.css are not exactly the same as those in the overall_header.tpl. It's not a big difference, but if it's important to you, just ignore the original subSilver.css and create sso.css copying the styles from overall_header.tpl and formIE.css.

We're done with the files, the rest is sysadmin stuff.

copying files to the new subdomains

That's easy, just take everything from templates/sso/images (leave the lang_english or any other language folders) and copy to http://i2.bgcanada.com/sso

Than take all lang_* folders and copy to http://i1.bgcanada.com/sso, so you'll have http://i1.bgcanada.com/sso/lang_english/

Now copy all smilies from phpbbroot/images/smilies to http://i1.bgcanada.com/smilies/

Now take the sso.css you created and copy to http://i1.bgcanada.com/sso.css

Last, take the whole sso directory and copy to the main domain - http://www.bgcanada.com/phpBB2/templates/ so that it's in the same folder next to subSilver.

Login to the admin panel and activate the new theme as usual. Login to your account and change your theme preference to sso. You still want to test before making it a default theme for everyone.

At this point you should be able to browse your forum with the new theme and everything should look like as if you were using subSilver.

Serving gzipped content

The rule is that all served files should be gzipped, with exception for images, because gifs, jpgs, pngs are already compressed.

To serve the normal html (php) pages gzipped, just use the built-in phpBB feature, log on to the admin panel and enable gzip compression.

To serve sso.css gzipped, ideally you should only create an .htaccess file and have Apache do it for you (more info). Unfortunately my host won't allow it, so I took the alternative path - have PHP gzip and serve the css file. To do so I created an .htaccess file http://i1.bgcanada.com/.htaccess and put in it:

AddHandler application/x-httpd-php .css

This affects all CSS files (but we have only one) and makes them php scripts. If your host allows you to use php_value in .htaccess, you can do the rest of the job by only using .htaccess. Otherwise create a http://i1.bgcanada.com/php.ini file and put in it:

[PHP]
default_mimetype = "text/css"
zlib.output_compression = On
zlib.output_compression_level = 6
expose_php = Off
auto_prepend_file = "pre.php"

The first line makes php send text/css header instead of the default text/html. Some browsers won't like CSS files served with text/html header. The second line enables compression and the next line sets the compression level (could be up to 9). 4th line is absolutely optional, just removes an extra header that PHP sends. The last line sets that all served php files should include the file pre.php as if you used include "pre.php" inside every PHP script. This is actually used later for the Expires header.

turning ETags off

That's super easy. Just add .htaccess rules in both i1 and i2 to say:
FileETag none

Expires header

To set the expires header, add these lines to .htaccess on both i1 and i2

ExpiresActive On
ExpiresDefault "access plus 2 years"

This makes all files - images and CSS - on i1 and i2 expire in 2 years, if that's too much/not enough, feel free to change.

If it doesn't work for you (it didn't for me, because of the host), you can go the php auto_prepend route described above and add in the pre.php file
header('Expires: ' .gmdate("D, d M Y H:i:s",time() + (60 * 60)) . ' GMT');
Feel free to set 60 * 60 to whatever you think makes sense for you. Note that this will only affect the CSS file, images will be served "normally". You can also have PHP serve all the images, like we did for CSS, but I think it's probably too much.

Sysadmin summary

There was a lot of if-then above so let me summarize what worked for me, but try your other options first to see how "liberal" your host is in order to do a better job than me.

http://i1.bgcanada.com/.htaccess

AddHandler application/x-httpd-php .css
FileETag none

http://i1.bgcanada.com/php.ini

[PHP]
default_mimetype = "text/css"
zlib.output_compression = On
zlib.output_compression_level = 6
expose_php = Off
auto_prepend_file = "pre.php"

http://i1.bgcanada.com/pre.php

<?php
header('Expires: ' .gmdate("D, d M Y H:i:s",time() + (60 * 60)) . ' GMT');
?>

Done!

We're done! Did it take more than an hour? Hope not, although with these computers and stuff, everything takes more time than expected.

Do you see anything missing? Or something that can be improved? Or something didn't work for you? Please post a comment. The whole posting is a bit fast-paced and written in a rush (I really need to go to bed), so if there's something unclear please ask.

Tell your friends about this post: Facebook, Twitter, Google+

11 Responses

  1. [...] YouTube Link to Article yahoo phpBB front-end optimization – 1 hour workshop » Posted at phpied.com on Friday, July 13, 2007 phpBB front-end optimization – 1 hour workshop July 13th, 2007 Let’s go ahead and optimize our phpBB installation for front-end performance. I’ll follow Yahoo’s 14 optimization rules, but only implement the ones that apply for phpBB. During this short workshop there will be no changes to the phpBB code, we’ll create a new template View Entire Article » [...]

  2. Stoyan Stefanov’s Blog: phpBB front-end optimization – 1 hour workshop…

  3. [...] … and my own phpBB optimization effort Post this entry to: » del.icio.us  » Digg  » Furl  » Newsvine  » reddit  » Y! [...]

  4. I think you have the “FileETags” declaration wrong – I think it should be “FileETag none” (no “s”). I get an Apache error when I have it set with “FileETags”.

    -mike

  5. Thanks, Mike! Corrected in the post.

  6. How to acquire Host Gator hosting, does it have any coupons newly, and are they valid?

  7. Im Handwerk gibt es einen neuen Trend: Auftragsbörsen wie My-Hammer. Dort können Interessierte ihre Aufträge einstellen und erhalten Gebote.

    Handwerker mit zu wenig Aufträgen können dann Aufträge entgegennehmen. Danach Bewerimg.

    Wie findet Ihr das?

    Gruesse
    Euer handwerio

  8. ла одета в легкое коротенькое платьице и ее красивые ножки сразу же привлекли мое внимание.
    Я как то инстинктивно сразу же остановился возле нее и приоткр
    пересесть на заднее сидения что мы и сделали. Там она сняла свое платьице и осталось в одних трусиках.
    Я принялся целовать ее нежную шейку спускаясь ниже я
    умела что я не хотел кончать но я был настолько возбужден что практически сразу же кончил в ее
    спросила она. “Алексей” – Ответил Я.
    - Лёша, почему вы боитесь заговорить со мной?

    Я медленно начал расстегивать ширинку на своих джинсах, наслаждаясь просмотром как эта сучка долбит себя вибратором!

    Я не стала возражать и они стали танцевать. Оля всегда была не равнодушна к моему мужу, он ей дико нравился, хотя она это скрывала. Да и Оля нравилась

    скользили по ним. Я проводила пальчиком от самой дырочки влагалища доверху, останавливаясь перед клитором на мгновение и снова опускаясь вниз.
    28 наверное уж точно. О планах на будущее я не загадываю, зачем гадать на кофейной гуще, но все же кое какие мысли витают,
    рит.
    И так меня в конце июня отправили в Омск на стажировку, приехали наши Японские менеджеры для
    , много старых каменных домов, мне это оч

    Олька обсасывал член моего Серёжки, заглатывая его в свой голодный ротик, закрыв глаза

    отправился к себе. Я тихо прошла в свою комнату, родители уже спали, и уже почти улеглась в постель, как вдруг раздался телефонный звонок. Я быстро подбежала и взяла трубку, чтобы не разбудить родителей. В трубке я услышала столь знакомый и долгожданный голос:
    сил и терпения и ему и мне, но после таких ласк ни он ни я не могли долго сдерживаться и вскоре волна оргазма накрыла нас с головой!
    я отложил колбу с трубочкой и поспешил к ней.
    Вика посмотрела на обмазанные густой белой массой, похожей на гипс, руки. |

    Минуту мы молча переводили дыхание. Потом девушка посмотрела на меня и произнесла:

  9. Hello there, just was aware of your weblog via Google, and found that it’s truly informative. I’m going to be careful for brussels. I’ll be grateful in the event you proceed this in future. A lot of other folks might be benefited out of your writing. Cheers!

  10. mymoneymonitore

    Anyone who reads Old and Middle English [b]my money monitor[/b] literary texts
    will be familiar with the mid-brown volumes of the EETS,
    with the symbol of Alfred’s jewel embossed on the front
    cover. Most of the works attributed to [b]my money monitor[/b] King Alfred or to
    Aelfric, along with some of those by bishop Wulfstan and
    much anonymous prose and verse from the pre-Conquest period,
    are to be found within the Society’s three series [b]my money monitor[/b]

  11. I used to struggle to find that little bit of extra money to
    pay the bills each month.

    Then I found PayBux, a pay to click website that pays you a
    few cents for every click.
    By following a proven method I have been able to make an
    additional $100 a month by only spending 20 minutes a day.S

    you can easily do the same. click on my referral link here and register to ProBux.

    http://www.probux.com/?r=masonb62

Leave a Reply