By KFSys
System Administrator
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.
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!
Accepted Answer
.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”.
URL rewriting involves changing the pattern of a URL without changing the underlying resource. It offers several benefits:
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:
- RewriteRule pattern substitution [flags]
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
.
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.
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.
Let’s delve into some more advanced use cases of the .htaccess rewrite rules:
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
.
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
.
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:
- RewriteEngine on
- RewriteCond %{HTTPS} !=on
- 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.
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.
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!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
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
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.