Redirect if subfolder is not present in url


I’m looking to create a redirect if url begins with /folder but does not contain /folder/subfolder



Should redirect to:


I’ve tried

RewriteCond %{REQUEST_URI} !^/folder/subfolder/.*$
RewriteRule ^(.*)$ /folder/subfolder/$1 [L]

But that doesn’t work. It needs to be a general redirect as I have many pages to redirect. It should be possible, right?

>Solution :

Have your .htaccess in following manner. There were 2 primarily things needed to be corrected in your nice attempts. 1st: You need not to match path after subfolder in condition part. 2nd: you are capturing everything including folder in rewrite part which we don’t need since on right side you are already mentioning it.

Please make sure to clear your browser cache before testing your URLs.

Following will not redirect URL in browser its an internal rewrite based on your attempts.

RewriteCond %{REQUEST_URI} !/?folder/subfolder/ [NC]
RewriteRule ^folder/(.*)/?$ /folder/subfolder/$1 [NC,L]

OR In case you want a real redirect and change URL on browser level then try following:

RewriteCond %{REQUEST_URI} !/?folder/subfolder/ [NC]
RewriteRule ^folder/(.*)/?$ /folder/subfolder/$1 [R=301,NC,L]

Leave a ReplyCancel reply