Home > other >  How do I redirect just my home page and keep rest of the URLs as it is?
How do I redirect just my home page and keep rest of the URLs as it is?

Time:10-05

I need to redirect some URLs as they are pointing to same page. For example:

https://www.example.com/home
https://www.example.com/Home
https://www.example.com/index.php

These all URLs need to refirect to:

https://www.example.com/

So I am using this in .htaccess file it is working fine :

Redirect 301 /home  https://www.example.com/

But the issue is when I try to access the URL like this:

https://www.example.com/home/sub

It redirects to resulting in 404:

https://www.example.com//sub

I need this URL to work as it is instead of 404 or any redirect:

https://www.example.com/home/sub

CodePudding user response:

Redirect 301 /home  https://www.example.com/

Because the mod_alias Redirect directive is prefix-matching and everything after the match is copied onto the end of the target URL. So, when you request /home/sub, /sub is copied on to https://www.example.com/, resulting in https://www.example.com//sub.

I imagine you also have mod_rewrite directives. You should avoid mixing redirects from both modules, so try the following instead using mod_rewrite at the top of the root .htaccess file:

RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(home|index\.php)$ / [R=301,L]

The condition that checks against the REDIRECT_STATUS environment variable ensures that only direct requests are processed, as opposed to internally rewritten requests which will result from having a front-controller pattern (which I assume you have later in the file).

You will need to clear the browser cache since the erroneous 301 (permanent) redirect will have been cached by the browser. Test with 302s to avoid potential caching issues.

Reference:

  • Related