Score:1

Redirect to folder only if root from other site referrer

dj flag

I have a redirect from root to subfolder. If user visits https://example.com it redirects to https://example.com/subfolder. But I want it not to redirect if referrer is my site, so user can reach root page.

For example:

  1. User visits https://example.com
  2. It redirects to https://example.com/subfolder
  3. User visits https://example.com/subfolder/file.html
  4. there's a link on this page to https://example.com and he follows it
  5. It must open https://example.com and not to redirect

Here is my .htaccess:

RedirectMatch ^/$ https://example.com/

Please, give me an advice to solve the problem, I'm poor on .htaccess rules.

Score:0
kz flag

Here is my .htaccess:

RedirectMatch ^/$ https://example.com/

This obviously doesn't redirect to /subfolder as you suggest. It would create an endless redirect loop.

However, you can't check the Referer header using a mod_alias RedirectMatch. You need to use mod_rewrite (or an <If> expression) instead.

For example:

RewriteEngine On

RewriteCond %{HTTP_REFERER} !^https://example\.com($|/)
RewriteRule ^$ /subfolder/ [R,L]

Note that the check for an empty URL-path (ie. ^$) is intentional. The RewriteRule pattern does not match the slash prefix.

Stas Ponomaryov avatar
dj flag
That's it, thanks. But If I user folows example.com link from example/subfolder/file.html it would redirect to example.com/subfolder/
kz flag
@StasPonomaryov Sorry, there was a typo in my answer. It should be `%{HTTP_REFERER}`, not `${...}`! I've updated my answer.
Stas Ponomaryov avatar
dj flag
Thanks, that was it!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.