简体   繁体   中英

allow direct url access to image only if requested by bot otherwise pass url to index.php file using .htaccess

.htaccess

#Disallowed
#RewriteCond %{REQUEST_URI} !.*\.png$ [NC]
#RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC]
#RewriteCond %{REQUEST_URI} !.*\.gif$ [NC]

#Allowed
RewriteCond %{REQUEST_URI}  !=/index.php
RewriteCond %{REQUEST_URI}  !.*\.php$ [NC]
RewriteCond %{REQUEST_URI}  !.*\.css$ [NC]
RewriteCond %{REQUEST_URI}  !.*\.js$ [NC]
RewriteRule . /index.php [L]

index.php

What I'm doing is handling all image url's with index.php and run the condition below. If bot is detected (googlebot,bingbot etc..) then display image otherwise run some stuff. Now I want to detect bot using .htaccess and allow image to open directly bypassing php part.

if(_bot_detected()){
  //echo image
}else{
  //redirect user to some page
}

I'm very new to web programming. After a lot of search i couldn't find any information that works for me. This is my first question to stackoverflow. Thanks for any help

I refer my answer based on the following _bot_detected() function:
https://gist.github.com/holgerhubbs/983a53ee21a9f6bff08d
If your function works different the matching would not be 100% equal.

The only thing that we have to check is if the request is for an image and not coming from a bot, because than we have to rewrite:

# Check if the URI is a physical file
RewriteCond %{REQUEST_URI} -f
# Check if the file has any kind off Image extension like:
# .gif .jpg .jpeg .tif .tiff .png .svg .bmp (case insensitive => [NC])
RewriteCond %{REQUEST_URI} \.(gif|jpe?g|tiff?|png|svg|bmp)$ [NC]
# check if the request in NOT coming from a bot
RewriteCond %{HTTP_USER_AGENT} !(bot|crawl|slurp|spider) [NC]
# If all Condition are satisfied than we rewrite to /index.php
RewriteRule ^.*$ /index.php [L]

Even my answer should match with your original php behavior, there is a height change that this matching criteria do not find all find bots.

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