mod_rewrite有多个查询字符串?

时间:2012-07-09 00:02:32

标签: apache .htaccess mod-rewrite

我正在尝试清理我博客上的一些网址,所以我决定查看mod_rewrite。我不知道我在做什么,所以我希望能得到一些帮助:P我有像http://kn3rdmeister.com/blog/post.php?y=2012&m=07&d=04&id=4这样的链接。虽然它有效,但人们仍然得到我希望他们拥有的内容,但我不喜欢他们必须查看所有查询字符串。我想将上述链接转换为http://kn3rdmeister.com/blog/2012/07/04/4.php

这就是我的.htaccess现在的样子。

RewriteEngine On
RewriteCond %{QUERY_STRING} ^y=([0-9){4})&m=([0-9]{2})&d=([0-9]{2})&id=([0-9]*)$
RewriteRule ^/blog/post\.php$ http://kn3rdmeister.com/blog/%1/%2/%3/%4.php? [L]
像我说的那样,我绝对无能为力:D

2 个答案:

答案 0 :(得分:3)

如果您使用的是apache 2.0或更高版本,如果这些规则位于.htaccess文件中,您将需要删除前导斜杠(前缀),以便您的正则表达式如下所示:

# also note this needs to be a "]"--v
RewriteCond %{QUERY_STRING} ^y=([0-9]{4})&m=([0-9]{2})&d=([0-9]{2})&id=([0-9]*)$
RewriteRule ^blog/post\.php$ http://kn3rdmeister.com/blog/%1/%2/%3/%4.php? [L]

当有人将http://kn3rdmeister.com/blog/post.php?y=2012&m=07&d=04&id=4放入浏览器的网址栏时,他们会将浏览器重定向到http://kn3rdmeister.com/blog/2012/07/04/4.php,新网址会显示在地址栏中。

我假设您的服务器上已经安装了一些设置来处理blog/2012/07/04/4.php等请求。

答案 1 :(得分:0)

首先,您应该定义您的网址!!!

像:

/blog显示front page

/blog/1234显示post 1234

/blog/date/2012显示posts by year

/blog/date/2012/06显示posts by year and month

/blog/date/2012/06/01显示posts by year and month and day

依旧......

第一个选项是将每个已定义的URL重写为index.php。您的index.php只需处理提交的GET参数。

### Do only if rewrite is installed
<IfModule mod_rewrite.c>

### Start rewrite and set basedir
RewriteEngine on
RewriteBase /

### Rewrite only if no file link or dir exists
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

### Rewrite frontpage
RewriteRule ^blog$ /index.php?action=showfront [L,QSA]

### Rewrite post
RewriteRule ^blog/([0-9]+)$ /index.php?action=showpost_by_id&id=$1 [L,QSA]

### Rewrite posts by date
RewriteRule ^blog/date/([0-9]{4})$ /index.php?action=showposts_by_date&year=$1 [L,QSA]
RewriteRule ^blog/date/([0-9]{4})/([0-9]{2})$ /index.php?action=showposts_by_date&year=$1&month=$2 [L,QSA]
RewriteRule ^blog/date/([0-9]{4})/([0-9]{2})/([0-9]{2})$ /index.php?action=showposts_by_date&year=$1&month=$2&day=$3 [L,QSA]

### Rewrite posts by tag
RewriteRule ^blog/tag/([a-zA-Z0-9_-]+)$ /index.php?action=showposts_by_tag&tag=$1 [L,QSA]

</IfModule>

在index.php中测试:     的print_r($ _ GET);     的print_r($ _ POST);

第二个选项是重写所有URL,index.php需要处理所有可能的URL。因此,首先它需要类似于路由器的东西,它将传入的URL分成几部分,然后发送请求的页面或错误页面。我最初会尝试这个血腥学校。

<IfModule mod_rewrite.c>

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^ index.php%{REQUEST_URI} [L]

</IfModule>

使用以下命令在index.php中测试:

print_r(explode('/', ltrim($_SERVER['PATH_INFO'], '/')));
print_r($_GET);
print_r($_POST);

第三种选择是使用PHP框架。框架可以帮助您快速编写代码。它为您提供了许多基类,如路由器。 (例如,ZendFramework,Flow3,Kohana,Symfony,CodeIgniter,CakePHP,yii等)。这会让你更高级。

第四种也是最懒的选择是使用像Wordpress这样的现成软件。

相关问题