.htaccess

The .htaccess file is a configuration file used by the Apache web server to configure various settings for a particular directory or set of directories within a website. The name ".htaccess" stands for "hypertext access", and the file is typically located in the root directory of a website.

The .htaccess file allows webmasters to control various aspects of the behavior of the Apache web server, including authentication, access control, URL redirection, error handling, and more.

Some common uses of the .htaccess file include:

  • Password protection The .htaccess file can be used to require a username and password to access a particular directory or file on the server. This is often used to protect sensitive information, such as private documents or administrative pages.
  • URL redirection The .htaccess file can be used to redirect requests for a particular URL to a different URL. This is often used when a website has moved to a new domain or when a page has been renamed or deleted.
  • Error handling The .htaccess file can be used to specify custom error pages for different types of errors, such as 404 (page not found) errors or 500 (internal server error) errors.
  • Rewrite rules The .htaccess file can be used to define rewrite rules that modify the URL of a request before it is processed by the server. This can be used to create more user-friendly URLs or to improve the search engine optimization (SEO) of a website.

It's important to note that the use of the .htaccess file is dependent on the server configuration and the specific Apache modules that are installed.

Making changes to the .htaccess file can have a significant impact on the performance and security of a website, so it's important to be familiar with the syntax and best practices before making any modifications.

Password protection

Password protection is a common use case for the .htaccess file. It allows you to restrict access to certain directories or files on your website by requiring visitors to enter a username and password. This can be useful for protecting sensitive information, such as private documents or administrative pages.

To implement password protection using the .htaccess file, you'll need to create a password file that contains the usernames and passwords for the authorized users. You can generate this file using the htpasswd command-line tool, which is included with Apache.

Once you've created the password file, you can create an .htaccess file in the directory that you want to protect.

Example .htaccess file that requires a username and password for all requests:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user

Let's break down what each line of this file does

  • AuthType Basic: This specifies that we're using basic authentication, which is a simple username/password scheme that's built into HTTP.
  • AuthName "Restricted Area": This sets the name of the protected area. This will be displayed in the authentication dialog box that visitors see when they try to access the protected directory.
  • AuthUserFile /path/to/.htpasswd: This specifies the path to the password file that contains the authorized usernames and passwords.
  • Require valid-user: This requires that visitors enter a valid username and password to access the protected directory.

With this .htaccess file in place, anyone who tries to access the protected directory will be prompted to enter a username and password. If they enter a valid username and password, they'll be able to access the directory. Otherwise, they'll be denied access.

URL redirection

URL redirection is another common use case for the .htaccess file. It allows you to redirect requests for a particular URL to a different URL. This can be useful when you've moved a page to a new location, or when you want to create a more user-friendly URL.

To implement URL redirection using the .htaccess file, you can use the Redirect or RewriteRule directives.

Example of an .htaccess file that redirects requests for a specific page to a new location:

Redirect 301 /oldpage.html http://www.example.com/newpage.html

Let's break down what each part of this directive does:

  • Redirect: This is the directive that tells Apache to redirect requests.
  • 301: This is the status code that will be sent back to the browser, indicating that the page has permanently moved. This is important for search engine optimization, as it tells search engines to update their indexes with the new URL.
  • /oldpage.html: This is the URL that we want to redirect. In this example, we're redirecting requests for a page called "oldpage.html".
  • http://www.example.com/newpage.html: This is the new URL that we want to redirect to. In this example, we're redirecting to a page called "newpage.html" on a different domain.

You can use RewriteRule directive to redirect requests. Here's an example that redirects requests for a specific page to a new location using a regular expression.

RewriteEngine On
RewriteRule ^oldpage\.html$ http://www.example.com/newpage.html [R=301,L]

Let's break down what each part of this directive does:

  • RewriteEngine On: This enables the rewrite engine, which is required for using RewriteRule directive.
  • RewriteRule: This is the directive that tells Apache to redirect requests using a regular expression.
  • ^oldpage\.html$: This is the regular expression that matches the old URL that we want to redirect. In this example, we're matching requests for a page called "oldpage.html".
  • http://www.example.com/newpage.html: This is the new URL that we want to redirect to. In this example, we're redirecting to a page called "newpage.html" on a different domain.
  • [R=301,L]: This sets the status code to 301 (permanently moved) and specifies that this is the last rule that should be processed.

Error handling

Error handling is an important aspect of any website, as it allows you to provide informative and user-friendly error messages when something goes wrong. With .htaccess, you can customize the way that Apache handles various types of errors, such as 404 Page Not Found errors.

To implement error handling using the .htaccess file, you can use the ErrorDocument directive.

Example of an .htaccess file that customizes the way that Apache handles 404 errors:

ErrorDocument 404 /404.html

Let's break down what each part of this directive does:

  • ErrorDocument: This is the directive that tells Apache to customize the way that it handles errors.
  • 404: This is the error code that we want to customize. In this example, we're customizing the way that Apache handles 404 Page Not Found errors.
  • /404.html: This is the URL of the custom error page that we want to display when a 404 error occurs.

With this .htaccess file in place, whenever a visitor requests a page that doesn't exist, Apache will display the custom error page instead of the default error message.

You can create your own custom error pages to provide more information to visitors, such as a list of links to other pages on your site.

Here's another example that customizes the way that Apache handles 500 Internal Server Error:

ErrorDocument 500 /500.html

In this case, we're customizing the way that Apache handles 500 Internal Server Error. When this error occurs, Apache will display the custom error page located at /500.html.

You can use the ErrorDocument directive to customize the way that Apache handles many other types of errors as well, such as 401 Unauthorized errors or 403 Forbidden errors.

Rewrite rules

Rewrite rules are a powerful feature of the .htaccess file that allow you to modify URLs on the fly. You can use rewrite rules to make your URLs more user-friendly, improve search engine optimization, and even redirect requests to other domains.

To use rewrite rules in your .htaccess file, you need to enable the RewriteEngine first. Here's an example of an .htaccess file that enables the rewrite engine and redirects all requests to a specific page to another page on the same domain.

RewriteEngine On
RewriteRule ^old-page$ /new-page [R=301,L]

Let's break down what each part of this directive does:

  • RewriteEngine On: This enables the rewrite engine, which is required for using RewriteRule directive.
  • RewriteRule: This is the directive that tells Apache to rewrite the URL using a regular expression.
  • ^old-page$: This is the regular expression that matches the old URL that we want to rewrite. In this example, we're matching requests for a page called "old-page".
  • /new-page: This is the new URL that we want to rewrite to. In this example, we're rewriting to a page called "new-page" on the same domain.
  • [R=301,L]: This sets the status code to 301 (permanently moved) and specifies that this is the last rule that should be processed.

With this .htaccess file in place, whenever a visitor requests the old URL "old-page", Apache will rewrite the URL to "new-page" and redirect the visitor to the new URL.

You can use regular expressions to match more complex patterns in the URL, such as capturing variables and using them in the rewritten URL.

Here's another example that rewrites URLs to remove the file extension:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [L]

In this case, we're checking if the requested file exists with a ".html" extension, and if it does, we're rewriting the URL to remove the ".html" extension.

This can make your URLs more user-friendly and improve search engine optimization by removing unnecessary file extensions.

Forcing HTTPS and Removing WWW

Forcing HTTPS and removing the "www" from your website's URL are common tasks that can be achieved using the .htaccess file.

These practices can help improve security and usability of your website, as well as ensure that visitors are always accessing the secure version of your site.

Example .htaccess file that forces HTTPS and removes the "www" from your website's URL:

RewriteEngine On
# Force HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Remove www from URL
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Let's break down what each part of this directive does:

  • RewriteEngine On: This enables the rewrite engine, which is required for using RewriteRule directive.
  • RewriteCond %{HTTPS} off: This checks if HTTPS is not already being used.
  • RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]: This forces the use of HTTPS by redirecting all requests to the secure version of the site. The [R=301] flag tells search engines and visitors that the redirect is permanent and to update their bookmarks, and the [L] flag tells Apache to stop processing any further rules.
  • RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]: This checks if the "www" is present in the URL.
  • RewriteRule ^(.*)$ https://%1/$1 [R=301,L]: This removes the "www" from the URL by redirecting all requests to the non-www version of the site. The %1 variable matches the domain name without the "www" prefix.

With this .htaccess file in place, all requests to your website will be redirected to the secure version using HTTPS, and any "www" in the URL will be removed.

This ensures that visitors are always accessing the secure version of your site and provides a more user-friendly URL.

You'll notice in the last code example there are two comments of:
# Force HTTPS
# Remove www from URL

Anything on its on line and after the # symbol the server will ignore. Great for keeping up with various functions on your .htaccess file by making a comment about it.

How to create a .htaccess file

Creating an .htaccess file is a simple process.

Here are the steps to create a .htaccess file:

  • Open a text editor such as Notepad, Sublime Text, or Atom.
  • Type in the configuration directives you want to include in your .htaccess file. Be sure to follow the proper syntax for each directive.
  • Save the file as ".htaccess" (with no file extension) in the root directory of your website.
  • Upload the .htaccess file to your website using an FTP client or file manager.
  • Verify that the .htaccess file is working properly by testing the directives you have included. You can do this by visiting your website and testing the functionality of each directive.

It's important to note that some web hosting providers may have restrictions on the use of .htaccess files or may require specific configurations.

Be sure to check with your web hosting provider before creating and uploading a .htaccess file to your website.

Always make a backup of your existing .htaccess file before making any changes.

Test any new directives thoroughly before deploying them to a live site.