简体   繁体   中英

Apache rewrite ignore images for processing permissions in PHP

I am noob to REGEX and have the following code in .htaccess

RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^uploads/(.*)$ download.php?file=$1 [QSA,L]

And the content of download.php file is

require_once ('users.php'); // user session 

$allowedExtensions = array(
    '.jpg',
    '.png',
    '.gif',
    '.ico',
);

$extension = substr($_GET['file'], -4);

// Requested file is not in allowed extension and is not a logged in user
If (!in_array($extension, $allowedExtensions) && !is_user()) {
    echo '<h1>Sorry, only members can download the files.</h1>';
    exit();
}

It works great and what it does is:

  1. Triggers verification whenever the files in "uploads" directory is served by Apache, specially for direct links.
  2. If it's a member (logged in user) serve all the files
  3. If it's not a member, only allow images, but deny access to any other files

But I think there is too much overhead in the download.php script to verify for image extenions each and every time, so I am trying to ignore the images directly from .htaccess rewrite rule. Looks like I have to change the following code

RewriteRule ^uploads/(.*)$ download.php?file=$1 [QSA,L]

to skip the images before passing to download.php, but don't know how.

Thank you!

Just add a condition that excludes those extensions:

RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|bmp)$ [NC]
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^uploads/(.*)$ download.php?file=$1 [QSA,L]

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