Mod Rewrite – Redirect a request URI from subfolder to a higher folder on the webserver

Last modified on:

I googled this for ages but I could not find the answer – all the posts I found were about how to just re-write how urls were displayed, because you would usually use the redirect command in .htaccess in order to redirect the browser request to a different resource on the server. You wouldn’t usually use mod re-write.

However, if you are redirecting requests for content from a sub folder to a higher level folder on the server, then you could get stuck in a circular redirect. You may also confuse visitors by displaying a url that they didn’t type in; so you need something a bit more special.

redirect 301 /directory/ /directory/article/
the above code would result in a circular reference!

The mod re-write command uses regex to define how you want apache to behave. For example, you have content currently being server from here: ‘/directory/article/page-name‘ but you want it to be seen to be seen to be ‘served’ from here: '/directory/page-name'.

To do this you need to enter the following in to your .htaccess file at the root of your site directory:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^directory/(((?!article).)*)/$ /directory/article/$1/index.html [NC,L]

This will work unless one of your page names has the same name as the folder that it is located (in this case ‘article’) as we are excluding this name from the URI re-write with the following code: (((?!article).)*)


Published on

in

by

Tags:

Leave a Reply

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