BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Redirect subdirectory to root using .htaccess

By Chaitanya Singh | Filed Under: WordPress

Choose the code as per your need –

1) Redirect from http://www.mysample.com/subdir/ {article-url} to http://www.mysample.com/ {article-url}

[code autolinks=”false”]
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.mysample.com
RewriteRule ^subdir/(.*)$ http://www.mysample.com/$1 [L,R=301]
[/code]

2) Redirect from subdomain’s subdirectory (sub.mysample.com/subdir/{article-url}) to http://www.mysample.com/{article-url}

[code autolinks=”false”]
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^sub.mysample.comm
RewriteRule ^subdir/(.*)$ http://www.mysample.com/$1 [L,R=301]
[/code]

3) From http://www.mysample.com/subdir/ to http://www.mysample.com/

[code autolinks=”false”]
RedirectMatch 301 ^/subdir/$ http://www.mysample.com/
[/code]

If you’re using non-www version of site then change it as-

[code autolinks=”false”]
RedirectMatch 301 ^/subdir/$ http://mysample.com/
[/code]

301 is also known as permanent redirect so the above code can also be written as –

[code autolinks=”false”]
RedirectMatch permanent ^/subdir/$ http://mysample.com/
[/code]

Temporary redirect
Above mentioned redirects are permanent, if you want temporary redirect then write it as –

[code autolinks=”false”]
RedirectMatch 302 ^/subdir/$ http://mysample.com/
[/code]

OR

[code autolinks=”false”]
RedirectMatch temp ^/subdir/$ http://mysample.com/
[/code]

These permanent and temp rules applies for all the examples shared in this tutorial.

3) From http://www.mysample.com/subdir/{article-url} to http://www.mysample.com/

[code autolinks=”false”]
# Permanent(301) redirect
RedirectMatch 301 ^/subdir/.*$ http://www.mysample.com/
[/code]

4) From http://www.mysample.com/subdir/{article-url} to http://www.mysample.com /mypage.html

[code autolinks=”false”]
RedirectMatch 301 ^/subdir/.*$ http://www.mysample.com/mypage.html
[/code]

Comments

  1. Gareth says

    August 29, 2013 at 9:38 PM

    Thanks for that. It got me out of a hole when I moved a site from a subdirectory to the root.

    Reply
  2. Nino says

    May 26, 2014 at 2:20 PM

    Hi, thanks for the article. If i want to redirect only the article url, from site/subdir/article-url to site/article-url, without redirect also the wp-admin and the uploads folder?
    Thanks

    Reply

Leave a Reply Cancel reply

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

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap