Htaccess Redirection
One of the most important uses of the htaccess file is Redirection. You can redirect pages between same or different domains.
Why Redirection needed?
We need redirection when we want to provide a new page instead of the old page. Sometimes, we move pages from location to another, so want to redirect users to updated URL. Here are a few scenarios:
- Need to redirect users from the current domain to another
- Need to redirect one page to another on the same domain
- Need to redirect one page to another on an external domain
- Redirect selected pages or directory to another location
- Any other page redirection based on certain condition
Note: Redirects Rules create impact on server load, site speed, search engine indexing so you need to be careful when implementing redirections on your website.
Redirect all URLs to another site
Redirect 301 / https://example.com/
This code will redirect all your website urls to https://example.com with server status 301 (Permanently Redirect).
Important Tips:
- If you do not provide a server status code, it will be 302 (Temporary redirect) by default.
- The first path here (current domain page/URL) will include the slash at the beginning.
- You can not include the https protocol and domain host for the current page/URL (in the first path here).
Redirect one page to another on the same domain
Redirect /page-1.html /page-2.html
This htaccess code will redirect page-1.html to page-2.html on the same domain.
Redirect one page to another on an external domain
Redirect /old-page.html http://example.com/new-page.html
This will redirect old-page.html on your website to http://example.com/new-page.html
Redirect directory to HTML page
RedirectMatch 301 /contact /contact.html
Using the above rule, when users visit www.yourwebsite/contact, they will be redirected to www.yourwebsite/contact.html.
Redirect same file/page to a different extension
RedirectMatch 301 "(.*)\.pdf$" "$1.html"
This htaccess rule redirects all .pdf files to .html files with the same name
Remove extra folder from the URL.
Suppose we need to remove extra folder from the URL or need to redirect based on common naming convention.
RewriteRule ^learn/(html.*)$ /$1 [R=301,NC,L]
Above htaccess rule with redirect https://website.com/learn/html-tutorial
to https://website.com/html-tutorial
if ‘html’ word is found after ‘learn’.
RewriteRule ^learn/php/(php.*)$ /$1 [R=301,NC,L]
Similarly, Redirect https://website.com/learn/php/html-table
to https://website.com/html-table
only if match “…learn/php/php…”
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |