How to Redirect to Different URLs with .htaccess file


Apache is the first layer of your website security. With Apache cinfiguration, you can do so many stuff like blocking specific request, limit request from specific server, block automatic crawlers, redirect to specific website or urls etc.

Below are few examples how you can redirect with Apache web server to improve better user experience. .htaccess file is the Apache configuration file where you can change settings. So put the below lines to change the apache settings.

Redirect all routes to specific URL

Put the below line to .htaccess to redirect all routes to specific routes, e.g. 

RewriteEngine  on
Redirect 301 /

Redirect only specific portion of site

If you only want to redirect specific portion of sites, add below lines.

Redirect "/admin/" ""

Redirecting a single URL

If you want to redirect only single URL to new page.

Redirect /path/to/old/url

Redirect from directory to an HTML file

If you want to add .html extension in URL, here is it

RedirectMatch 301 ^/about

Redirecting error messages

If you want to redirect to specific pages in case of 404 error page,

ErrorDocument 404

Forcefully redirect to HTTPS

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

Forcefully add www in the URL

If you forcefully want to add WWW in the URL.

RewriteCond %{HTTP_HOST} ^
RewriteRule (.*)$1 [R=301,L]

Remove WWW from the URL

RewriteCond %{HTTP_HOST} ^
RewriteRule (.*)$1 [R=301,L]

I hope it will help you.