Reading Time: 5 minutes
Apache .htaccess Logo

In this tutorial, we discuss the Apache .htaccess file and the many ways it can be modified and configured to suit your specific needs. We will be reviewing how to configure .htaccess redirects, rewrites, and add other customizations.

Let's say you have decided to change domain names or have one web address on your site that you want to redirect to a completely different location. Using a .htaccess redirects, you can send visitors to the new page or site automatically!

The Apache software provides a directory-level configuration called Hypertext Access or .htaccess file. This hidden file is usually found in your website's public_html folder. To modify it, SSH into your server account and modify the file using your favorite command line text editor. We can also create the file ourselves and upload it to the server using FTP/SFTP or SCP. Additionally, most control panels allow us to modify the .htaccess file using a native file manager.

Note:
You should always back up important files before you modify them. Do not delete the existing .htaccess file unless it is empty or you are sure it is ok to do so.

Your website's .htaccess file may already contain important settings that need to remain in place. If your .htaccess file has existing settings, you will need to add the new code to what is already there.

If your site was built for you and you aren't entirely familiar with your site code, you may need to seek assistance from a designer or developer when adding new .htaccess settings.

Simple Redirects

Redirect an Individual Page

A URL redirect tells the server it will be sending this traffic to another destination. To redirect domain traffic permanently, use 301. For a temporary redirect, use 302. The following entry sends any visitors who are trying to go to test.com/old.html to test.com/new.html.

Redirect 301 /old.html http://www.test.com/new.html

Redirect an Entire Website

When we want to change our domain name while keeping the old one, one of the best options is to set up a simple 301 redirect from the root directory of the old domain (/) to the new one.

Redirect 301 / http://www.test.com/

Simple Rewrites

Rewrites (mod_rewrite) are similar to redirects (mod_alias). They repoint a target URL or class of URLs to another URL. However, in most cases, it is better to use the mod_alias directive instead because it is simpler and requires less configuration. 

We should limit its use to situations where there are already other rewrite rules in the .htaccess file. When there are Redirect rules and RewriteRule directives in place, RewriteRule directives have hierarchical priority over Redirect rules, regardless of the order of appearance in the configuration file. There are several use cases in which we can implement RewriteRule directives. 

Rewrite a Site Address From WWW To Non-WWW

To automatically redirect a visitor who types in http://www.test.com to http://test.com and remove the www section from the web address, use the below command.

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^test\.com
RewriteRule (.*) http://test.com/$1 [R=301,L]

Rewrite a Site Address From Non-WWW To WWW

If, on the other hand, we would want to send visitors from http://test.com to http://www.test.com, we can use the below rule.

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^test.com [NC]
RewriteRule ^(.*)$ http://www.test.com/$1 [L,R=301]

Rewrite a Site Address Without Changing the URL

This will redirect a specific URL to an external domain without the visitor being aware of the redirection, as the URL will remain the same in the browser’s address bar. 

RewriteCond %{REQUEST_URI} ^/any_url/
RewriteRule ^(.*)$ https://external_domain.com/any_url/ [P]

Rewrite a Page Without Changing the URL

This redirect is especially handy if we have renamed or moved a page. Customers who access the old page will be sent to the new one without being aware of the change as the address bar in their browsers will remain intact.

RewriteEngine  on
RewriteRule    "^/my_old_page\.html$"  "/new_page.html" [PT]

Rewrite to Force HTTPS Connections

All connections will be mapped to the secure port (443) with this rule, so even direct HTTP requests will not load an insecure connection. 

RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Rewrite File Names Without the Extension

We can redirect any request to file types to the same file without showing the extension. You can include several file extensions at a time, as in the below example, in which we are redirecting php, html, and htm files. The expected behavior is to go from https://liquidweb.com/random_page.php to https://liquidweb.com/random_page.

RewriteEngine on
RewriteRule ^/?(.*).(php|html|htm)$ /$1 [R=301,L]

Rewrite a Subdomain to a Directory

The rule has to be placed in the subdomain’s root directory. It will redirect any request to the subdomain to the directory we choose. For instance, if we want to redirect https://blog.liquidweb.com to https://liquidweb.com/blog/, then the bellow rule will work perfectly.   

RewriteEngine on
RewriteRule ^(.*)$ https://liquidweb.com/blog/$1 [L,NE,R=301]

Additional Setups 

Custom Error Pages

Error pages can often be boring, generic, and ambiguous. We can create custom pages on our dedicated server that match our site’s overall theme and style and are easier to interpret by visitors. 

ErrorDocument 401 http://any.domain.com/how_to_get_access.html
ErrorDocument 403 default
ErrorDocument 404 /404.html
ErrorDocument 500 "This is a funny error message."
ErrorDocument 500 /custom_file.html

These redirects can be configured at the top of the .htaccess file. As shown in the above examples, they follow this pattern:

  • The ErrorDocument directive. 
  • The error code used for the redirect (401, 404, etc.). 
  • The action to be executed. It can be text displayed in the visitor’s browser, a local or external URL, or a file (like 404.html). 
Note:
The special word “default” is used to set the web server’s default error page.

Password-Protected Content

There is an easy way to password-protect specific content via .htaccess. We just need to add the following code to the .htaccess file in the directory we want to protect.

AuthType Basic
AuthName "Protected"
AuthUserFile "/home/myuser/.htpasswds/passwd"
require valid-user

We need to make sure to reference the correct path to the .htpasswds directory. The last step would be to add users and passwords to the passwd file within .htpasswds. The correct terminology to add users is user:password.

You can generate a password here or from the command line (using the MD5-based password algorithm).

$ openssl passwd -1
Password: mypass
Verifying - Password: mypass
Password generated: $1$UyoTN20N$WeWXiTlJE3iivdK9ToFea.
$ cat /home/myuser/.htpasswds/passwd
my_valid_user:$1$UyoTN20N$WeWXiTlJE3iivdK9ToFea.

An alternative method to generate a secure password is to use the pwgen program. The pwgen program uses flags to generate passwords that are designed to be as secure as possible. To install it, run one of the following commands on your VPS Server or Cloud Dedicated server.

#DEBIAN/UBUNTU
apt-get install -y pwgen
#FEDORA/RHEL
dnf install -y pwgen
#CENTOS
yum install -y pwgen
pwgen -synBcN1 24
"#wi>d;fhsK{Ky^%MxETmf9u

If you are concerned with hotlinking or want to reduce your bandwidth usage, try testing this option to eliminate that issue.

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?domain.com/ [nc]
RewriteRule .*.(gif|jpg|png)$ http://domain.com/img/hotlink_no.png [nc]

Conclusion

We’ve seen several practical uses of the .htaccess file, and there are many more. However, we should point out that it’s best to use the main configuration files if possible as they offer better overall performance and security. If we don’t have root access to the server, modification options are available in the management panel. This is usually the best way to set up .htaccess rules on a per-directory basis without too much hassle and is an incredibly flexible tool to take the most out of your hosting environment. 

We Can Help! 

We pride ourselves on being The Most Helpful Humans In Hosting™!

Our Support Teams are filled with experienced Linux technicians and talented system administrators who have intimate knowledge of multiple web hosting technologies, especially those discussed in this article.

If you are a Fully Managed VPS server, Cloud Dedicated, VMWare Private Cloud, Private Parent server, Managed Cloud Servers, or a Dedicated server owner and you need additional or more specific information about your .htaccess file, setting up redirects, or any other concerns, you can reach out to our award-winning support via a LiveChat, or give us a call at 1-800-580-4985. Our technical support staff is always available to answer questions if you need additional information about this article, 24 hours a day, 7 days a week, 365 days a year. Support is also available via our ticketing systems by emailing us at support@liquidweb.com.

About the Author: Misael Ramirez

I have a degree in mechatronics; the career suited me because I'm always trying new things. I have a wide range of interests, but mainly I love music, movies (old ones), and physics.

Have Some Questions?

Our Sales and Support teams are available 24 hours by phone or e-mail to assist.

1.800.580.4985
1.517.322.0434

Latest Articles

5 Alternatives to GitHub

Read Article

5 Steps to Install and Configure osquery on CentOS 7 & 8

Read Article

Five Steps to Create a Robots.txt File for Your Website

Read Article

Premium Business Email Pricing FAQ

Read Article

Microsoft Exchange Server Security Update

Read Article