pQB*_*pQB 2 wordpress .htaccess mod-rewrite url-rewriting
如何为文件夹中已存在的文件编写规则以指向不同的位置。例如,用于将文件wp-content/uploads/夹中对pdf 文件的任何请求重写为页面download/?q=$1。
我在 SO 中看到了一个有关移动 pdf 文件的相关问题,其中包含以下内容
# checks that the request is for a file that *does not* exist
RewriteCond %{REQUEST_FILENAME} !-f
# make sure we've not already redirected to the uploads directory
# (in case it doesn't exist in there either)
RewriteCond %{REQUEST_URI} !^/wp-content/uploads/
# the rule matches against either pdf, zip or xls.
RewriteRule ([^/]*\.(pdf|zip|xls))$ /wp-content/uploads/$1 [NC,L,R=301]
Run Code Online (Sandbox Code Playgroud)
但我想要相反的效果。对我现有的文件进行重定向,并为不存在的文件保留 404 not found。
我尝试了不同的方法,但没有运气。想知道.htaccess根文件夹中的WordPress默认文件是否干扰了这个。如何将pdf的所有请求重写为自定义页面?
编辑:
该.htaccess文件位于wp-content/uploads文件夹中。
关于 WordPress 重写 API,我已经在自定义插件中具有以下功能:
function add_rewrite_rules($aRules) {
$new_rules = array(
'exams/([^/]+)/([^/]+)/?$' => 'index.php?pagename=exams&type=$matches[1]&city=$matches[2]',
'exams/([^/]+)/([^/]+)/subject/([^/]+)/?$' => 'index.php?pagename=exams&type=$matches[1]&city=$matches[2]&subject=$matches[3]'
);
return $aRules + $new_rules;
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,这些函数允许我们为 WordPress 指定额外的重写规则,如重写 API/添加重写规则文档中所述。因此,它不应影响.htaccess文件中指定的规则的内容。
假设您的 WP 安装在域的根目录下,它将是:
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_URI} /wp-content/uploads/
RewriteRule ([^\/]+\.pdf)$ /download.php?q=$1 [NC,L,R=301]
Run Code Online (Sandbox Code Playgroud)
第一行(!从您的示例代码中删除)仅匹配现有文件,因此如果 PDF 文件不存在,您将获得标准 404。
第二个条件将匹配限制为仅文件/wp-content/uploads/夹中的现有文件,因此不会重定向http://example.com/example.pdf。
最后,RewriteRule(受两个先决条件的影响)重定向上传文件夹中以.pdf扩展名结尾的任何现有文件,以/downloads.php将文件名作为q参数传递。
因此,如果文件夹中存在,http://example.com/wp-content/uploads/2016/04/filename.pdf将被重定向到。http://example.com/download.php?q=filename.pdffilename.pdf/wp-content/uploads/2016/04/
我已经在本地虚拟 WP 安装中检查了这个解决方案并且它有效,所以我希望这会有所帮助。
编辑:如果你.htaccess的上传文件夹中有一个,只有这样就足够了:
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ([^\/]+\.pdf)$ /download.php?q=$1 [NC,L,R=301]
Run Code Online (Sandbox Code Playgroud)
您是否尝试过评论中的建议(放入一些垃圾.htaccess以检查它是否已启用)?
另一个拍摄是将规则移到根.htaccess...
| 归档时间: |
|
| 查看次数: |
2767 次 |
| 最近记录: |