Forum Moderators: phranque

Message Too Old, No Replies

Preventing direct access to a page

         

miyazaki

5:50 pm on Dec 30, 2008 (gmt 0)

10+ Year Member



Hello,

Imagine I had a web page called internal.html - but, I wanted people to access this resource through the url www.example.com/external.html. AND, on top of that, I wanted www.example.com/internal.html to return as 'Forbidden'.

I've been trying to achieve this effect with .htaccess for ages now, and am not being very successful. This is my best attempt so far:


RewriteCond %{ENV:myvar} !val
RewriteRule ^internal.html$ internal.html [F]
RewriteRule ^external.html$ internal.html [ENV=myvar:val,N]

This doesn't quite work though. external.html is indeed rewritten to internal.html, and then it isn't forbidden, cause the 'myvar' environment variable is set. BUT, .htaccess then re-runs itself again, throwing away the environment variables, and so external.html becomes 'Forbidden' as well.

How does one get around this? Replies very much appreciated...

miyazaki

5:53 pm on Dec 30, 2008 (gmt 0)

10+ Year Member



p.s. I did have success with:

RewriteCond %{ENV:REDIRECT_STATUS} !200

but that seems really cheesy! Is there a better way?

Caterham

5:58 pm on Dec 30, 2008 (gmt 0)

10+ Year Member



You wouldn't run into this problem, if you could use your rules in per-server context instead of per-dir context.

throwing away the environment variables

They are now named
REDIRECT_oldvar
.

Use

%{THE_REQUEST}
instead which contains the request string like
GET /foo?args HTTP/1.1
if you can't avoid the per-directory context.

[edited by: Caterham at 6:00 pm (utc) on Dec. 30, 2008]

g1smd

6:02 pm on Dec 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You need to test
%{THE_REQUEST}
to see if the internal filepath is being directly asked for by the client or whether it is the result of an internal rewrite.

miyazaki

6:08 pm on Dec 30, 2008 (gmt 0)

10+ Year Member



Perfect! Thanks guys.

jdMorgan

6:12 pm on Dec 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Adapted from the usual method posted here, which generates a 301 redirect instead of a 403:

# Forbid direct client access to "/internal.html"
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /internal\.html\ HTTP/
RewriteRule ^internal.html$ - [F]
#
# Internally rewrite requests for "external.html" to "internal.html"
RewriteRule ^external.html$ internal.html [L]

Unless recursive .htaccess execution is actually required, do not use [N], as it is usually highly-inefficient. If further rules actually need to be processed (but without re-executing previous rules), then simply omit the [L] flag.

Jim