User:Terrye/Configuring .htaccess for phpBB

If you do a web search, then you will find many cookbooks on how to set up your .htaccess files. Some warn of the performance impacts of using them. Yes, using .htaccess files can degrade overall server throughput by a few percent, but if set up correctly they can also improve perceived user responsiveness by factors, so put quite simply: you don't have any alternative.

= General guidelines =

If .htaccess files are enabled then Apache will check every directory on the path from your root directory to the one which contains the script file and parse it if the directory contains one. So:
 * Whenever practical, use a single .htaccess file in your web root directory to do what you need, and
 * Remove any .htaccess files in subdirectories, except in the rare occasions when directory-specific access files are the only way to achieve what you need. In the case of phpBB you should remove all  .htaccess files provided in the standard install as these functions can be done more simply in the single central file.

The .htaccess file contains a set of Apache directives and the best reference for understanding these is in the Apache2 Documentation.

Note that that (i) you will only be able to use directives tagged as valid in .htaccess files; and (ii) directives relating to a specific Apache modules will only work if your HSP's Apache configuration loads the requires Apache2 module(s).

Also note that your PHP runtime system will not normally be running under mod_php, so the php* directives will result in a parsing error. You will need to configure your own php.ini as described in Configuring php.ini for phpBB.

The general techniques for debugging directives in an .htaccess</tt> file are problematics, as you may not have any or immediate access to the Apache error log and rewrite logging is normally disabled for performance reasons. The best technique is to add changes one line at a time and try exercising each change by requesting a page from site. If an Apache error is thrown up by the change then you have already localised it to one line.

You can use these files for a lot of functions but the following sections are relate to those which are appropriate to a phpBB service.

= Enable correct caching and file compression =

It is essential that you let the client browsers know which files can be cached safely. Three header responses are used to do this. The Expires</tt> header defines a 'sell-by date' which gives an indication of until when the file can be assumed to be valid. This is used to short-circuit normal file access. Set the end-dates according to volatility, so "access plus 1 day" will mean that browsers will revalidate every day. You can normally get away with a week or even a month. # #   ExpiresActive On ExpiresByType text/css        "access plus 1 month" ExpiresByType text/javascript "access plus 1 month" ExpiresByType image/x-icon   "access plus 1 month" ExpiresByType image/jpeg     "access plus 1 week" ExpiresByType image/gif      "access plus 1 week" ExpiresByType image/png      "access plus 1 week"
 * 1) Define Expires dates for static contnet

The Cache-Control header is an alternative mechanism which you should specify as well.

# # <FilesMatch "\.(css|js|gif|jpe?g|png|pdf)$"> Header add "Cache-Control" "public, max-age=604800" </FilesMatch>
 * 1) Set the Cache control max-age = 1 week for CSS, JS, PDF and image file-types

Note that when the user does an explicit refresh then this validity date information is ignored by the Browser. Also depending on the browser options configuration, the user may also have chosen to do this on the first reference in this browser session as well. In this case, it negotiates with the server to validate any cached content and Etag</tt> or Last-Modified</tt> headers are used instead. This optimises web network traffic and delays, and effectively allows the client to ask "is the version that I have still valid?". Note that in the case of script generated content, the script still has to run but the client and server can decide to bypass transfer of its output. Don't use the Apache Etag default for static files as this includes the file's Inode</tt> and this can change from request to request if your HSP is using a server farm, because different requests might be handled by different servers.

# # FileETag MTime Size
 * 1) Omit Inode from Etag to prevent cache invalidation on server swap

Use mod_deflate to compress all outbound traffic. This add a few percent to the CPU cycles but typically reduced network volumes by 3x (and network latencies accordingly). The Accept-Encoding directive helps any intervening proxies negotiate optimum transfer. # #  AddOutputFilter DEFLATE js css AddOutputFilterByType DEFLATE text/html text/plain test/css text/xml application/xml <FilesMatch "\.(js|css|xml|html)$"> Header append Vary Accept-Encoding </FilesMatch>
 * 1) Set up DEFLATE compression from text stream types (Compression doesn't help on compressed formats such as JPEG)

= Create default error files =

You can specify your own custom error handlers to tailor the response to the user when Apache raises an error. . These can be a script giving a user-friendly and informative message or a simply static HTML message as shown below. You can find examples on the web, and see the Apache documentation for further discussion. # # ErrorDocument 500 /error_500.html ErrorDocument 401 /error_401.php ErrorDocument 403 "Access is forbidden" ErrorDocument 404 Default
 * 1) Define Custom Error Handlers

= Specify a Default Charset = PhpBB already issues an explicit Content-Type: text/html; charset=UTF-8</tt>, but your HSP may have defined a default character set in the base Apache configuration. If so, then this will override any Content-type headers in non-phpBB HTML. An easy way to prevent this happening is to default to UTF-8 for all web pages. Also set the default language according to your installed templates. # # AddDefaultCharset utf-8 DefaultLanguage en-GB
 * 1) pass the default character set

= Specify a site-specific contact email address = Your HSP will have define its own contact email address, but you should override this, even if you are flagging up that you won't accept email requests. # # SetEnv SERVER_ADMIN do_not_reply@yourdomain.com
 * 1) set the server administrator email

= Lock down access to private files = There are two methods for preventing access to forbidden files and directories. The first is to use a combination of the  <FilesMatch> </tt>, Order</tt> and Deny</tt>. However perhaps the simplest method is to use a couple of RewriteRule</tt> statements as follows. Note that you will need to change the highlighted directory name to reflect the name of your actual phpBB root directory. Also note the convention adopted here that any web request for any file or directory beginning with an underscore or period will be rejected as well. This sweeps up any attempt to access .htaccess</tt> files and makes it easy to have a _private</tt> directory, for example. Options All -Indexes # # RewriteEngine  On RewriteBase     / RewriteRule phpbb3 /(cache|files|includes|install-old|language|store)/ -  [forbidden] RewriteRule /(\.|_|config\.php$|common\.php$)                         -  [forbidden]
 * 1) Deny access to forbidden directories and files

= Lock down processing of different web request types = PhpBB only uses the GET and POST methods, so any others should be viewed with great suspicion. Note that some web crawlers use HEAD to validate changes to your sitemap.xml</tt>, and some browsers will issues a PROPFIND. As an anti-spamming measure you also want to prevent any posts that come directly from outside your domain or have a blank Referrer. If you use POST directly from your own scripts (e.g. to automate routine phpBB housekeeping) then to prevent this rule failing your own scripted posts include the RewriteCond</tt> which checks for a private cookie; and delete this line otherwise. # # RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD|PUT|LOCK|) RewriteRule .*                -         [F] # # RewriteCond %{REQUEST_METHOD} POST RewriteCond %{HTTP_COOKIE}    ! somePrivateId RewriteCond %{HTTP_REFERER}   ! yourforumdomain [OR] RewriteCond %{HTTP_USER_AGENT} ^$ RewriteRule (.*)              -         [F]
 * 1) Reject HTTP methods which phpBB doesn't use
 * 1) Reject POSTs which don't contain your special cookie, come from your domain or have a blank user agent

= Prevent Hotlinking to Avatars and other images = This one is a little paranoid, but if you are noticing off-site references to the image content then you might wish to stop this. Note that the files subdirectory is already forbidden. # # RewriteCond %{REQUEST_URI} (styles/|images) RewriteCond %{HTTP_REFERER} ! yourdomainname RewriteRule .*             -            [F]
 * 1) block off-site access to style and image furniture.  Access from a forum page should include the page as referrer