How to Rewrite URL in .htaccess


how to rewrite urls in htaccess

.htaccess is a great utility provided by Apache web server to setup URL redirection and rewrites. Here are some commonly used examples of how to rewrite URL in .htaccess.

 

How to Rewrite URL in .htaccess

Before we start, make sure you have module in Apache. Here’s how to enable mod_rewrite in Apache:

  1. On Ubuntu
  2. On CentOS

 

The basic syntax of URL Rewrite in .htaccess file is


RewriteRule pattern substitution [flags]
  • RewriteRules – Server directive for defining rewrite rules
  • Pattern – A regular expression that matches the desired string in requested URL
  • Substitution – Where the requested URL should be sent for processing
  • [Flags] – optional parameter to modify the rule. Here’s the detailed documentation about Rewrite Flags.

.htaccess can have more than one rewrite rules. However, Apache will execute them in the defined order only. When Apache gets a URL that matches one of the rewrite rules, it will remap that URL to the destination URL.

 

Redirect all links from www.example.com to example.com

If you want to force your site URLs from www to non-www versions, then you can use the following rewrite rule


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

 

Redirect all links from example.com to www.example.com

If you want to force your site URLs from non-www to www version, then you can use the following rewrite rule


RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^/?$ "http\:\/\/example\.com\/" [R=301,L]

 

Redirect all links from oldexample.com to newexample.com

If you want to redirect URLs to a totally different domain


RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !oldexample.com$ [NC]
RewriteRule ^(.*)$ http://newexample.com/$1 [L,R=301]

 

Redirect all URLs from one directory to another directory

Let’s say you want to redirect all URLs from /blog/archives to /newarchives/


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

 

Redirect all URLs from HTTP to HTTPs

If you want to force HTTPS on your site


RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

 

Redirect non-exiting links to index.php

This will redirect all the pages and folders that don’t exist on your website, that is, give “404 page not found” error to index.php. If they are present, then they will load 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>

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!