htaccess to redirect a url, file, or folder

3.7k 0

Sometimes, in web and app development or deployment operations, you need to insert some rules in the .htaccess file at your root folder of your hosted domain in order to redirect or rewrite some URLs, folders or files. Some of the use cases are:

  • Redirect old content to the updated one.
  • Force Google to deindex old content to optimize SEO.
  • Mantain a user-friendly URL structure on a website.
  • Create a subdomain for architecture purpose.
  • Customize not found 404 and other error pages…

When I have faced with one of this tasks, it was not always easy to find and understand the proper solution I was searching for. That is why I tried to list in this post the most usual rules we need to apply on an htaccess file, with their corresponding examples.

The examples below can be entered into your .htaccess file exactly as shown. Just make sure to adjust the actual path to the file so the .htaccess file knows where it’s located. Also, if you see the domain example.com, change this to your own domain name.

Redirecting all URLs

The following line redirects all URLs on your site to the new site.

Redirect 301 / https://example.com/

Redirecting a single URL

Using Redirect in an .htaccess file enables you to redirect users from an old page to a new page without having to keep the old page. For example, if you use index.html as your index file and then later rename index.html to home.html, you could set up a redirect to send users from index.html to home.html. For example:

Redirect to a local site file

Redirect /path/to/old/file/old.html /path/to/new/file/new.html

Redirect to an external site file

Redirect /path/to/old/file/old.html https://www.example.com/new/file/new.html

The first path

The first path to the old file must be a local UNIX path, NOT the full path. So, if the .htaccess file is in the directory /example.com, you would not include /home/username/example.com in the local UNIX path. The first / represents the example.com directory. If the old file was in that directory, you would follow the / with the old file name.

The second path

The second path to the new file can be a local UNIX path, but can also be a full URL to link to a page on a different server or the same server.

Examples of redirects

Redirect from a directory to an HTML file

RedirectMatch 301 ^/blog/about /blog/about.html

Redirect from an index.html file to a different directory

Redirect /index.html /new/

Redirect from index.html to default.html

Redirect /index.html /default.html

Redirect a local /private directory to another site’s private directory

Redirect /private/ https://www.example.com/private/

Load a .gif file from a different site

Redirect /img/logo.gif https://www.example.com/images/logo.gif

Using Regular Expressions

If you want to use a Regular Expression to redirect something, use the RedirectMatch directive:

RedirectMatch "^/oldfile\.html/?$" "https://example.com/newfile.php"

Redirecting error messages

You can also redirect 404 errors. Instead of throwing a 404 page, this redirects to the homepage of the website.

ErrorDocument 404 https://example.com/

Redirecting an old directory to new directory

This redirects files in a old directory (/blog/archives) to a new directory (/archives). The file must exist in the new directory to function.

RewriteRule ^blog/archives/(.*)$ /newarchives/$1 [R=301,NC,L]

Redirect non-existing pages to index.php

If a visitor attempts to access a page that doesn’t exist, they are presented with a 404 error. You can instead redirect any request to a non-existing page to your index.php file (or any index file) by adding the following code in your .htaccess:

Options +SymLinksIfOwnerMatch 
RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

If your index page isn’t index.php, just change the last line to your actual index file. Then the visitor is redirected back to your home page.

Automatically loading a subdirectory

This example redirects the ROOT domain’s URL to any subdirectory. In this example, it automatically loads example.com/subdir1:

RewriteEngine on
RewriteRule ^$ /subdir1/ [L]

Forcing www in the URL

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

Removing www in the URL

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

Rewriting a URL

This example rewrites a URL to another URL. This rewrites example.com/1.html to example.com/abc.php?id=1.

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9]+).html /abc.php?id=$1 [QSA,L]

The following explains the rules above:

  • ([0-9]+) allows any digit, and only any digit, 1 or more times.
  • ([a-z-]*) allows any lowercase letter, plus “-” for word separation, 0 or more times. If you want it to support uppercase too, use “([a-zA-Z-]*). For example:RewriteRule ^place/([a-zA-Z-]*).html /place/abc.php?id=$1 [QSA,L]
  • [QSA,L] appends this to your internal scripting query string, and makes it the Last rewrite rule executed.

After using this method, you can retrieve the webpage with either address type. This is handy for retro-fitting a website that was not designed with mod_rewrite in mind. This is good because it does not destroy any bookmarks saved on users computers.

The following redirects all links to files or folders that do not exist to index.php. However, if the file or directory does exist, it loads normally:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>;

Redirect HTTP to HTTPS for your site

For this purpose, we have 2 equivalent options. To make it by listening the 80 port requests:

RewriteEngine on
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [NE,R=301,L]

Or by checking if the request is not HTTPS and then redirect:

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

Create a subdomain with htaccess

If you want to convert any of your subfolders into a subdomain URL of your example.com domain, you can easily achive this adding this to your htaccess:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^subfolder\.example\.com$ [NC]
RewriteRule ^((?!subfolder/).*)$ /subfolder/$1 [L,NC]

I found this very useful when your hosting provider does not allow you to exceed a certain number of subdomains at the hosting control panel. 😉

Carlos Pérez

Digital manager, tech lead, product designer, full stack engineer, web and app developer, SEO, digital marketing, automation and AI expert.

Leave a Reply

Your email address will not be published. Required fields are marked *