简体   繁体   中英

Prevent direct access to file in URL

There is a file foo.php, which is inside /hello/bar.

So if the user says

/hello/bar/foo.php # Access forbidden

/hello/bar/foo # Redirect to foo.php

So far what I have done is this, in .htaccess in / ,

RewriteEngine on
RewriteRule "^hello/bar/foo$" "hello/bar/foo.php" [L]
RewriteRule "^hello/bar/foo.php$" "-" [F]

But this doesn't seem to work. Putting both the URLs, the server sends a 403 error. How can I correct this?

Once a set of rewrite rules are applied, the result is handed back to the URI parser which, if the URI changed, will re-invoke the rewrite rule set (either in the same .htaccess or a different one, depending on the new URI).

What this means, is that the [L] flag you used does not fully stop rewrite processing, it just stops processing the current cycle thru the rules set.

So, in your .htaccess, the 1st rule rewrites hello/bar/foo to hello/bar/foo.php and [L] ends the current rewriting. The URI parser, seing that the URI changed, will re-invoke rewriting again from the top. The 1st rule won't apply this time but the 2nd rule causes Forbidden (aka HTTP 403 - Forbidden).

So, you need a way to stop this cycling. In later versions of Apache, you can use the [end] flag instead of [L] . This will end all rewriting completely.

RewriteEngine on
RewriteRule "^hello/bar/foo$" "hello/bar/foo.php" [END]
RewriteRule "^hello/bar/foo.php$" "-" [F]

See https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM