Apache服务器URL重写
比如这是一张图片地址为:D:\Tim\PhpStudy2018\PHPTutorial\WWW\Uploadfile\Uploads\admin\2018-05-25\5b07b9cc1494c.jpg
需要在浏览器中以短地址方式显示这张图片,比如打开短地址: 127.0.0.1/Uploadfile/file/5b07b
这时需要用的URL重写:
要点1.建立控制器GetfileController.class.php
header()函数参考:http://www.jb51.net/article/127401.htm
<?php namespace Admin\Controller; use Think\Controller; class GetfileController extends InitializeController { public function index() { $filesDB = M('files'); $code = $_GET['code']; $web_path = dirname(THINK_PATH); //D:\Tim\PhpStudy2018\PHPTutorial\WWW\Uploadfile if(!isset($code)){ header("Content-Type:image/png"); echo file_get_contents($web_path .'/image/none.png'); exit(); } $row = $filesDB->where(" `keycode` = '$code' ")->find(); if(!isset($row) || !isset($row['filepath'])){ header("Content-Type:image/png"); echo file_get_contents($web_path .'/image/none.png'); exit(); } $filepath = $row['filepath']; //比如: ./Uploads/admin/2018-05-25/5b07b9cc1494c.jpg $filetype = $row['filetype']; //"application/octet-stream"; $filename = $row['filename']; header("Content-Type:$filetype"); if(strlen($filetype)>5 && strtolower( substr($filetype, 0, 5))!="image"){ header('Content-Disposition: attachment; filename="'.$filename.'"'); } echo file_get_contents($web_path . $filepath); } } ?>
要点2.数据库中设计到文件的类型:

要点3.Thinkphp框架中修改.htaccess文件:
(.htaccess文件在项目的根目录下)
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^file/([0-9a-zA-Z]*+) admin.php/Admin/Getfile/index?code=$1 [L]
</IfModule>
附:
Apache重写URL指南 http://man.chinaunix.net/newsoft/ApacheManual/misc/rewriteguide.html

浙公网安备 33010602011771号