Home > Software engineering >  Redirect from folder-URL only to another URL (but allow subfolder-URLs)
Redirect from folder-URL only to another URL (but allow subfolder-URLs)

Time:10-12

I would like to redirect from

http://example.com/folder

to

http://example.com/

But still be able to access

http://example.com/folder/subfolder

without being redirected. So only the specific "folder"-URL should be redirected to root. Is that doable? Can't seem to exclude the subfolders.

Current code (that is redirecting folder/subfolder as well) is:

Redirect folder https://www.example.com/

Many thanks!

CodePudding user response:

Problem is with the Redirect directive that matches any URI that starts with the given pattern. Here it will match any URI that starts with /folder.

You can use RedirectMatch for precise matching using regex:

RedirectMatch 302 ^/folder/$ https://www.example.com/

Or use RewriteRule:

RewriteRule ^/?folder/$ https://www.example.com/ [L,R=302,NC]

Note that I have kept leading / optional in RewriteRule. That makes this rule compatible with Apache server config where it should start with a / and .htaccess where leading / is not matches since .htaccess is per directory directive and Apache strips the current directory path (thus leading slash) from RewriteRule URI pattern.

  • Related