Home > Enterprise >  301 redirect folder root
301 redirect folder root

Time:12-18

I'm struggling with a fairly simple 301 redirect.

I have several redirects for pages which all work fine - eg

Redirect 301 /folder/mypage1.html https://www.example.com/folder/mypage2.html.

However now I want to redirect from a folder root to another page, I don't however want any of the other pages in the folder to redirect.

So /myfolder/ should redirect to https://www.example.com/mypage.html but /myfolder/mypage.html should not redirect.

I've tried:

Redirect 301 /myfolder/ https://www.example.com/mypage.html but this doesn't work.

I apologize for the newbie question that probably has a very simple answer.

CodePudding user response:

Use RedirectMatch, which matches using a regex, rather than simple prefix-matching (as with Redirect) to redirect requests for the folder only.

For example:

RedirectMatch 301 ^/myfolder/$ https://www.example.com/mypage.html

Both Redirect and RedirectMatch belong to the same Apache module: mod_alias

You will need to clear your browser cache if you have been experimenting with 301 (permanent) redirects. Test first with 302 (temporary) redirects to avoid potential caching issues.

CodePudding user response:

With your shown samples, please try following htaccess rules file. This uses apache's THE_REQUESTvariable to perform rewrite.

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

RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s/myfolder/\s [NC]
RewriteRule ^  mypage.html [L]
  • Related