htaccess notes
Examples using RewriteEngine
Force https
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
Simple cookie based gatekeeper
RewriteEngine On
RewriteBase /path/to/
RewriteRule \.html$ gatekeeper.php [L]
then gatekeeper.php
<?php
$path = $_SERVER['REQUEST_URI'];
$filename = array_pop(explode("/",$path));
if( $filename === "" ) $filename = "index.html";
require_once("auth.php"); # this defines function auth() -> bool
if( !auth() ) {
http_response_code(403);
echo "Access denied";
exit();
}
# if we get this far, just dump the file
if( is_file($filename) ) {
readfile($filename);
exit();
} else {
http_response_code(404);
echo "$filename not found.";
exit();
}
Star redirect
So that everything goes through a single, central .php file
RewriteEngine On
RewriteBase /
RewriteRule ^index.php index.php [L]
RewriteRule ^(.*)$ index.php [L,QSA] # everything handled by the index
and then index.php is simply
<?php
define('SiteTitle',"pt2");
require("../php/wiki.php");
This takes the task of resolving URI's to filenames completely out of the httpd server's hands.
For example, on this wiki, requests for files will search from leaf to root, so for example
a request for pt2_bg1.jpg will find that file in the root even though the url is
https://pt2.allsup.co/webdev/apache2/htaccess/pt2_bg1.jpg — this makes things convenient
for things like CSS where the .css references pt2_bg1.jpg, but if I place a file with
the same name in a subdirectory, it overrides for that subdirectory and any below it.
(I can make use of this when giving subdirectories topic-specific backgrounds like /editor/vim.)
Error pages
ErrorDocument 404 /404.html
Domain Redirect
Suppose we want to redirect to a new domain, preserving the path, so e.g. http://old.com/mr/flibble maps to https://new.com/mr/flibble and so on. See this stackoverflow.
For redirecting from an old test-domain to this wiki:
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ https://pt2.allsup.co/$1 [END,R=301]
Check Speling
There is a mod_speling which will try to spelling correct urls.
Sometimes this is annoying, and took me a while to find out about it.
To disable, put this in .htaccess
CheckSpelling Off
Until I knew of this it was very annoying, and led in part to the idea of how PT works
where only the .php files are in the webspace that httpd sees, and these handle fetching
and serving files and pages from a separate page and version store.