.htaccess bonus tricks

Léo Colombaro edited this page Apr 14, 2014 · 3 revisions

Here is a collection of bonus .htaccess tricks.

These snippets are not part of the default .htacess file because they may or may not work on your host. Add them at the end of the original .htacess, and simply delete them if that seems to break your site.

Bonus: Force non-WWW

After the YOURLS block in your .htaccess file, add the following script.

# BEGIN WithoutWWW
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
# END WithoutWWW

This directive MAY or MAY NOT work on your host (ie http://sho.rt/stuff might work fine and http://www.sho.rt/stuff might not). If it doesn't work, simply stick to one domain, either with or without www.

Bonus for newer Apache version

If you are running Apache 2.2.16 or later, you can simply replace the whole <IfModule > directive with the following :

FallBackResource yourls-loader.php

This should speed things by a couple micro-seconds on every request (seriously).

Bonus: block access to directories without a default document

This snippet will prevent the web server from listing the content of a directory if there is no default document (ie index.html, index.htm, index.php etc...)

<IfModule mod_autoindex.c>
   Options -Indexes

Bonus: block access to config files

The config.php file does not output anything under normal circumstances, but you can still prevent anyone from trying to access it:

<files config.php> 
   order allow,deny 
   deny from all