Question

HTACCESS Rewrites: An In-Depth Guide with Practical Examples

  • Posted on May 23, 2023• Last validated on May 23, 2023
  • Apache
  • KFSysAsked by KFSys

The .htaccess file is a powerful tool that allows you to configure settings on a per-directory basis for websites hosted on Apache servers. One of its most widely used capabilities is URL rewriting. In this article, we will explore how htaccess rewrites work and provide some examples. We will also delve deeper into more complex solutions to illustrate the full potential of this functionality.


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
May 23, 2023
Accepted Answer

Understanding the .htaccess file

.htaccess is a configuration file used by web servers running the Apache software. This file can be used to customize the server’s settings for your website without altering the global configuration file, thereby making it easier to manage the server configuration for individual sites or directories. The “.htaccess” name simply stands for “Hypertext Access”.

What are URL Rewrites?

URL rewriting involves changing the pattern of a URL without changing the underlying resource. It offers several benefits:

  1. Search Engine Optimization (SEO): URL rewriting can help to create clean, easy-to-read URLs that are more search-engine friendly.
  2. Simplified Navigation: URL rewriting can simplify complex URLs to make them more user-friendly.
  3. Security: By obfuscating certain parts of a URL, rewriting can provide an additional layer of security.

How does URL Rewriting work in .htaccess?

In .htaccess files, URL rewriting is accomplished through mod_rewrite, a module that uses a rule-based rewriting engine to rewrite requested URLs on the fly. At the core of each rewrite rule are two main parts: the Pattern and the Substitution. Here’s the basic syntax:

  1. RewriteRule pattern substitution [flags]
  • Pattern: This is a regular expression that will match the URL(s) you want to rewrite.
  • Substitution: This is the URL you want to redirect to when a match is found.
  • Flags: These are optional parameters that can change the functionality of the rule.

Let’s look at a simple example:

RewriteEngine on
RewriteRule ^about.html$ aboutus.html

In the above example, ^about.html$ is the pattern and aboutus.html is the substitution. If a user tries to access the about.html page, they are redirected to aboutus.html.

More Complex Examples

Let’s move on to more complex scenarios. Suppose we have a dynamic website where user profiles are accessed via a URL like www.example.com/profile.php?user=username. We can rewrite this URL to a more user-friendly format, such as www.example.com/username.

RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1

Here, ^([a-zA-Z0-9_-]+)$ is a regular expression that matches any alphanumeric string (including underscores and hyphens). When a match is found, it’s passed as a parameter to profile.php.

Another common use case is implementing a trailing slash redirect, which ensures each of your URLs points to a directory rather than a file. This is beneficial for SEO purposes.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*[^/])$ $1/ [L,R=301]

In this example, the RewriteCond directive sets conditions for the RewriteRule to be triggered. The two conditions check that the request isn’t for a file and that the URL does not end with a slash. If both conditions are met, the RewriteRule adds a trailing slash to the URL and issues a 301 (permanent) redirect.

Conclusion

In this article, we have discussed the basics of htaccess rewrites, starting with an overview of the .htaccess file, followed by URL rewrites and their importance. We then dived into the syntax of RewriteRules and rounded up with more complex examples.

Remember, while URL rewriting with .htaccess is powerful, it should be used carefully. Incorrect use can lead to misconfigured websites and negatively impact SEO. Always test your .htaccess rules thoroughly and only work on a live site when you’re confident they’re correct.

KFSys
Site Moderator
Site Moderator badge
May 23, 2023

Let’s delve into some more advanced use cases of the .htaccess rewrite rules:

1. Rewriting URLs for Pagination:

Let’s say you have a blog that displays a list of posts, and it has pagination. You might have URLs like www.example.com/blog?page=2. You can make these URLs more readable by rewriting them to something like www.example.com/blog/page/2.

Here’s how you could do that:

RewriteEngine on
RewriteRule ^blog/page/([0-9]+)$ blog.php?page=$1

This rule rewrites blog/page/2 to blog.php?page=2.

2. Removing File Extensions:

You may want to remove the .php extension from your URLs for a cleaner look. This can be achieved as follows:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

This set of rules will remove the .php extension from your URLs. So, www.example.com/about.php will become www.example.com/about.

3. Enforcing HTTPS:

You may want to enforce HTTPS across your website for security reasons. You can use the following rule to automatically redirect all HTTP traffic to HTTPS:

  1. RewriteEngine on
  2. RewriteCond %{HTTPS} !=on
  3. RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This rule will redirect all non-HTTPS requests to the same URL, but using the HTTPS protocol.

4. Preventing Image Hotlinking:

Hotlinking is a practice where one website uses another’s resources, like images, directly on their site. This can consume bandwidth and slow down the original website. You can prevent image hotlinking using the following rules:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourwebsite.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

This rule will deny any request for an image if the referring website is not your own website.

5. Redirecting WWW to Non-WWW:

You might want to ensure your website is accessed with or without ‘www’. The following rule will automatically remove ‘www’ from your URLs:

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

Remember, these are just a few examples of what you can do with .htaccess rewrites. With a good understanding of the syntax and a little bit of creativity, you can do a lot more!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.