服务HTML文件(如果存在),否则使用mod_rewrite重定向到索引

时间:2013-08-28 20:32:31

标签: php apache .htaccess mod-rewrite

我想写一个重写规则来执行以下操作:如果服务器上存在以下任何文件作为特定目录中的静态html文件,那么我希望.htaccess提供该静态文件。否则,我希望将 id (斜杠后面的第一个数字)作为查询参数传递给www.gallery.com/index.php

www.gallery.com/1-driving-to-the-beach.html   
www.gallery.com/2-swimming.html

示例:假设www.gallery.com/2-swimming.html不存在于服务器上的html文件中。我希望将 id = 2 发送到我可以使用

/index.php
<?php
ob_start();
?>
<html></html>
<?php
file_put_contents('2-swimming.html', ob_get_contents());
?>

问题:

  1. 我的.htaccess文件应该包含哪些重写规则?
  2. 当.htaccess重定向网址时,如何抓取index.php中的 ID

1 个答案:

答案 0 :(得分:2)

将此规则添加到文档根目录中的htaccess文件:

RewriteEngine On
RewriteCond %{REQUEST_FILENANE} !-f
RewriteCond %{REQUEST_FILENANE} !-d
RewriteRule ^([0-9]+)-(.*)\.html$ /index.php?id=$1 [L]

将请求的ID部分发送到index.php作为参数 id

相关问题