Notes about Apache’s htaccess aka HyperText Access files.
Prevent Apache listing directory contents
To hide a directory from listing via a browser add an .htaccess inside the directory that contains the following:
IndexIgnore *
The *
is a wildcard that matches all files. E.g. You could use *.jpg
to hide only the JPG files (with a .jpg extension). The list of files to ignore should be space seperated.
Redirecting pages
You can redirect content using mod_alias, via the RedirectMatch or Redirect directives.
Note that the RedirectMatch directive can be greedy, depending on the regexp used, so best to put any Redirect directives first to ensure they are matched.
<IfModule mod_alias.c>
Redirect 301 /an/old/url.html http://example.com/a/new/url.html
Redirect 301 /another/old/url.html http://example.com/another/new/url.html
RedirectMatch 301 ^/an http://example/everything-else-beginning-with-an.html
</IfModule>
See Apache Module mod_alias for mod_alias docs and HTTP/1.1: Status Code Definitions for a list of HTTP status codes.
You can also redirect using mod_rewrite.
Domain name redirects
If you have a load of domain names but only want people to use one of them, you can redirect with mod_rewrite:
<IfModule mod_rewrite.c>
RewriteEngine on
# Domain redirects
RewriteCond %{HTTP_HOST} ^example\.co\.uk [OR]
RewriteCond %{HTTP_HOST} ^example\.asia [OR]
RewriteCond %{HTTP_HOST} ^example\.biz [OR]
RewriteCond %{HTTP_HOST} ^example\.eu [OR]
RewriteCond %{HTTP_HOST} ^example\.net [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.co\.uk [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.asia [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.biz [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.eu [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.net [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com
RewriteRule /?(.*) http://example.com/$1 [R=301,L]
</IfModule>
Prevent access to files in a directory / subpath
You can use mod_rewrite to prevent someone accessing files in a directory, or, more accurately, pages under a sub-path of the URL.
For example, if you want to prevent anyone accessing files under http://example.com/private/
, then you can send back a 404 as follows:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^private/(.*)$ /404.html [R=404,L]
</IfModule>
Note: For whatever reason this won’t actually redirect to 404.html it’ll just issue a 404 response.