Common Uses for .htaccess files

Common Uses for .htaccess files

We have compiled a brief list of common directives that can be utilized for your sites. A .htaccess file is primarily designed to interact with an Apache web server, however, our Windows Shared servers, using IIS, are able to use the ISAPI rewrite module which allows for certain directives to be readable for the IIS web server. For those directives please see the link below:

Can I use a .htacccess file to password protect a directory?

Yes, on our LINUX servers you can use a .htaccess file to password protect a directory. The .htpasswd file will need to be created outside of the public_html directory, listing the file in the public_html/www directory or in a subsequent directory will make it visible to the public.

After creating the .htpasswd file, edit it and include your username and passwords as seen below:

Usertest:286755fad04869ca523320acce0dc6a4
TestUser:286755fad04869ca523320acce0dc6a4
BobTheAdmin:286755fad04869ca523320acce0dc6a4

Note: All of the passwords listed are the same, but the goal is to illustrate that they are an MD5 hash.

Add the following your .htaccess file:

AuthUserFile /path/to/.htpasswd/file/goes/here
AuthName "Password Protected Directory Title"
AuthType Basic
Require valid-user

Note: Change the AuthUserFile path to the .htpasswd you had just created.

Enabling Case Insensitive URLs for my Linux site

In a LAMP stack, the Apache web server will expect the URL you enter to be exact, this includes the casing of the letters. This can be overridden by either installing the Apache module mod_speling and implementing the following code to your .htaccess file:

CheckSpelling on

Rewriting all URL requests to WWW.

You can use the .htaccess file to direct all of the content to the www instance of a domain.

Add the following rule set to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Rewriting HTTP requests to HTTPS

You can use the .htaccess file to direct all of the content to the HTTPS instance of a domain.

Add the following rule set to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} !^on$
RewriteRule (.*) https://yourdomain/$1 [R,L]

Create a Wildcard Subdomain Redirect

The .htaccess file can be used as a catch-all for your domain if you have set up a wildcard subdomain entry in your DNS zone file to point the content to the server. You can then have the .htaccess file configured to redirect all of those requests to the main domain instance.

Add the following rule set to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.mydomain\.dk$ [NC]
RewriteCond %{HTTP_HOST} ^(.*)\.mydomain.dk$ [NC]
RewriteRule ^(.*)$ http://mydomain.dk/ [P,L,QSA]