How to Redirect to Different URLs with .htaccess file

  370 views   1 year ago Apache

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. https://laravelcode.com/ 

RewriteEngine  on
Redirect 301 / https://laravelcode.com/

Redirect only specific portion of site

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

Redirect "/admin/" "https://www.laravelcode.com/admin/"

Redirecting a single URL

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

Redirect /path/to/old/url https://www.laravelcode.com/path/to/new/url

Redirect from directory to an HTML file

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

RedirectMatch 301 ^/about https://www.laravelcode.com/about.html

Redirecting error messages

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

ErrorDocument 404 https://laravelcode.com/page-not-found

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} ^laravelcode.com
RewriteRule (.*) https://www.laravelcode.com/$1 [R=301,L]

Remove WWW from the URL

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

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]