简体   繁体   中英

How can I use an htaccess rewrite rule to redirect away from an existing file?

I have a directory called users which contains sub directories for each user. Eg my directory structure might look like:

users/
    .htaccess
    UserAccess.php
    foo/
        baz.txt
    bar/
        passwd.txt

I want to prevent users from accessing other users files. Therefore, I wrote a php script which checks the path and prints the file contents or not. The problem is that the script is not being run, but rather apache is trying to access the files directly.

My .htaccess in the users/ directory is:

RewriteEngine on
RewriteRule ^users/ UserAccess.php

A user would then try to access http://mywebsite.com/users/username/file . Eg http://mywebsite.com/users/foo/baz.txt .

The key point is that http://mywebsite.com/users/username/ is a REAL directory.

How do I fix this to accomplish what I want?

EDIT:

RewriteEngine on
RewriteRule . UserAccess.php

doesnt work either.

if your URL is like http://example.com/users/... adding:

RewriteCond %{REQUEST_FILENAME} -f

should make it work.

I've set an example on my computer with the following .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^testdir readHTACCESS.php

and it works just fine...

LINK

为了防止直接访问,您可以对UserAccess.php以外的所有文件Deny from all使用Deny from all

我猜你需要使用mod_rewrite的选项看看这里

I'll assume that mod_rewrite is alive and running on your server, and all we're dealing with is how to use it. :-)

I suggest you specify an explicit path to UserAccess.php. Do you know what the "working directory" is for your rewrite rule?

RewriteRule ^/users/ /users/UserAccess.php

I've tested this and it works for me. If it doesn't for you, then perhaps there's a configuration problem that's not just the rewrite rule. If that's the case, it would be very helpful to know what you're seeing in your access.log and error.log.

You can also perhaps simplify what's going on in PHP by feeding the filename as a variable:

RewriteRule ^/users/(.+\.txt) /users/UserAccess.php?what=$1

That way, you can skip parsing $_SERVER['REQUEST_URI'] and just test for the existence of the file prior to sending it out with readfile() or equiv.

The answer was that the subfolder (foo in the example) had permissions 700. This caused a 403 response before the rewrite rule was parsed. I changed the permissions to 701 and everything worked.

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