Search code examples
apache.htaccessmod-rewritehttp-redirect

Redirect subdirectory to root URLs using .htaccess


Slight tweak on some other questions/answers I found here, which didn't work for me.

My website had a subdirectory of www.mywebsite.eu/subdirectory where all the website's pages were located. I have now moved all the files to www.mywesbite.eu. The /subdirectory has essentially been deleted.

How can I do a .htaccess redirect that makes any /subdirectory URL redirect to a URL without the subdirectory.

Here's an example: www.mywebsite.eu/subdirectory/webpage.html now needs to be www.mywebsite.eu/webpage.html

Instead of doing a redirect on all the pages on my website, I'm hoping there's an easier way to just say "if someone requests a URL with /subdirectory in it, take them to exactly the same URL, just without /subdirectory at the start"

I originally tried

RewriteRule ^subdirectory/(.*)$ www.mywebsite.eu/$1 [L,R=301]

but that didn't work. I have this at the very start:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

Solution

  • You can use this rule in your DOCUMENT_ROOT/.htaccess file:

    RewriteEngine On
    
    RewriteRule ^subdirectory/(.*)$ /$1 [L,NC,R=302,NE]