我如何在这里正确使用mod_rewrite?

时间:2015-01-04 01:19:53

标签: apache mod-rewrite

我想使用.htaccess文件重写我的网址,如下所示:

输入:http://example.com/posts/18/title

输出:http://example.com/posts/post.php?id=18&title=title

我将.htaccess文件放在我的网络服务器的posts目录中。

这是我的.htacess文件的内容:

# Enable Rewriting
RewriteEngine on

# Rewrite post URLs
#   Input:  /posts/18/this-is-the-post-title
#   Output: /posts/post.php?id=18&title=this-is-the-post-title
RewriteCond %{QUERY_STRING} id=(\d+)&title=([A-Za-z0-9-]+)
RewriteRule ^/posts/post.php /%1/%2? [R=301]

当我直接转到http://example.com/posts/post.php?id=18&title=title时,它会转到http://example.com/18/title

我知道我在某个地方犯了一个错误,但我没有想法。

1 个答案:

答案 0 :(得分:0)

你正在倒退。另外,如果我正确理解了这个问题,你不需要301重定向,而只需要内部更改用于Apache和PHP。

你想要做的是:

# Enable Rewriting
RewriteEngine on

# Rewrite post URLs
#   Input:  /posts/18/this-is-the-post-title
#   Output: /posts/post.php?id=18&title=this-is-the-post-title
RewriteRule ^/posts/(\d+)/([^/]+) /posts/post.php?id=$1&title=$2
相关问题