【发布时间】:2011-03-10 12:48:24
【问题描述】:
我正在编写一个小网络应用程序,我需要重写一些规则,因为我很懒,不想在 PHP 中这样做。 而且我看到自己写了很多规则,也许一无所获,所以我寻求您的建议和帮助!
注意:
- YEAR is 4 digits
- MONTH is two digits
- DAY is two digits
- TITLE is a long word including -, like : i-am-a-title
- NB_PAGE is only number (no limit here)
- The trailing slash is not mandatory
我需要满足这个方案:
1. /YEAR/MONTH/DAY/title => index.php?title=TITLE
2. /page/NB_PAGE => index.php?page=NB_PAGE
3. /YEAR/MONTH/DAY/ => index.php?year=YEAR&month=MONTH&day=DAY
4. /YEAR/MONTH/DAY/page/NB_PAGE => index.php?year=YEAR&month=MONTH&day=DAY&page=NB_PAGE
5. /YEAR/MONTH/ => index.php?year=YEAR&month=MONTH
6. /YEAR/MONTH/page/NB_PAGE => index.php?year=YEAR&month=MONTH&page=NB_PAGE
7. /YEAR/ => index.php?year=YEAR
8. /YEAR/page/NB_PAGE => index.php?year=YEAR&page=NB_PAGE
9. /archives/ => _cache/archive.html
10. /feed/ => /_atom.xml
11. Everything NOT starting with a _ is considered a title and will redir to index.php?title=TITLE
还有:
-
它不能阻止现有文件夹:(这部分可以很容易地编写脚本来为应用程序根目录的每个文件夹添加重写规则。)
- 如果有一个名为 image 的目录并且我使用 http://host/image/test.png 浏览我将访问 image 并且我不应该在 $_GET['title'] 变量中获得 /image/test.png
它不能阻止真实文件,如果我想要http://host/file-that-exists.txt,我应该拥有它。如果文件在目录中,请参阅下面的注释。
其实我是带着这个来的:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*).php(/?$) $1.php [L,QSA]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/(\w*\b)(/?$) index.php?title=$4 [L,QSA]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})(/?$) index.php?year=$1&month=$2&day=$3 [L,QSA]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/page/([0-9]+)(/?$) index.php?year=$1&month=$2&day=$3&page=$4 [L,QSA]
RewriteRule ^([0-9]{4})/([0-9]{2})(/?$) index.php?year=$1&month=$2 [L,QSA]
RewriteRule ^([0-9]{4})/([0-9]{2})/page/([0-9]+)(/?$) index.php?year=$1&month=$2&page=$3 [L,QSA]
RewriteRule ^([0-9]{4})(/?$) index.php?year=$1 [L,QSA]
RewriteRule ^([0-9]{4})/page/([0-9]+)(/?$) index.php?year=$1&page=$2 [L,QSA]
RewriteRule ^(archives\b)(/?$) _cache/archive.html [L,QSA]
RewriteRule ^(feed\b)(/?$) /_atom.xml [L,QSA]
RewriteRule ^page/([0-9]+)(/?$) index.php?page=$1 [L,QSA]
RewriteRule ^([^_/].*)(/?$) index.php?title=$1 [L,QSA]
</IfModule>
但它不适用于 /image/ 示例,我觉得我正在走上一条糟糕的道路……我再说一遍,我不想在 PHP 中处理这个问题。我真的认为重写对我来说更灵活。
非常感谢您的帮助和指导。
希望我的英语不错,因为它不是我的母语。
【问题讨论】:
-
你的英文很好,但我真的很喜欢这个标题:D
-
@The Guy Of Doom: KISS - 保持简单,愚蠢(以防你不知道:P)
-
@n00b 我知道,但这仍然很有趣。
标签: php apache mod-rewrite