2

Given a homepage at domain.com (e.g., https://example.com/), I want:

  1. outside requests to only be able to visit the homepage and no subpages
  2. that homepage to successfully redirect visitors to a subpage (for example, https://example.com/page1.html)

I can accomplish #2 with some simple JavaScript and window.location.href = example.com/page1.html. But for #1, is there a way to reject access to internal pages if the referrer is coming from my domain.com? Basically the flow I'm looking for is:

  1. outside visitor visits https://example.com/
  2. https://example.com/ redirects visitor to, for example, example.com/page1.html
  3. any attempt to visit example.com/page1.html directly fails with a 404

I get that this may all seem nonsensical in terms of what it does. That's by design. I want a website that sends visitors to internal pages, but only if they get there through the homepage redirecting them to it.

Stephen Ostermiller
  • 99,822
  • 18
  • 143
  • 364
mix
  • 195
  • 1
  • 1
  • 6

2 Answers2

3

There is a simple way if you want the rules to be followed but not enforce them against deliberate spoofing. This looks something like this:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://www.example.com/.*$
RewriteRule (.+) - [R=404,L]

Someone with intent on bypassing this can spoof the referrer though. A better way would be for you to enforce visiting the home-page first in your code. Basically, you read a cookie and if it is not there, redirect to the home page. If it is there, do not redirect. Make the home page be the only one that sets the cookie, and they have to visit the home page first.

In PHP the function called session-start can be used for this since it starts or resumes a session. You did not say what back-end you are using but there are probably equivalents in other languages.

Itai
  • 6,037
  • 2
  • 32
  • 48
2

I've not tried this as my environment makes doing so tricky, but I posit something along the following lines will work in .htaccess

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{HTTP_REFERER} !www\.example\.com [NC]
RewriteRule ^ -[R=404,L]

Of-course replace www.example.com with your actual domain, and if your default file is not index.php change the second line as well.

The idea is to allow /index.php to be accessed without restriction thanks to the second line, with lines 3 and 4 being used to produce a 404 error for anything else which does not have a referer. I note that you specifically asked for a 404 error. That error should more correctly be a 403 - Access denied.

davidgo
  • 8,560
  • 1
  • 21
  • 30