多个不同的 php 页面需要友好的 URL - url 重写


Multiple different php pages need to be friendly URL - url rewrite

我有php网站有多个不同的php页面:

Example:
http://www.mywebsite.com/post.php?group_id=10&post_id=1
http://www.mywebsite.com/image.php?group_id=10&img_id=1
http://www.mywebsite.com/poll.php?group_id=10&poll_id=1
http://www.mywebsite.com/group.php?group_id=10
http://www.mywebsite.com/user.php?uid=158
....

我需要这些 URL 如下所示:

http://www.mywebsite.com/post/10/1
http://www.mywebsite.com/image/10/1
http://www.mywebsite.com/poll/10/1
http://www.mywebsite.com/group/10
http://www.mywebsite.com/user/158
....

注意:不是只有我有的这些页面,我有很多这样的页面。

我的htAccess文件如下:

<IfModule mod_rewrite.c>     
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?q=$1 [NC,L]
</IfModule>

我的 htAccess 重定向到单个索引页面的问题,如何使 htAccess 重定向到每个页面及其参数。

有新规则分别处理 2 个参数和一个参数:

<IfModule mod_rewrite.c>     
    RewriteEngine On
    RewriteRule ^(group)/('d+)/?$ $1.php?group_id=$2 [NC,L,QSA]
    RewriteRule ^(user)/('d+)/?$ $1.php?uid=$2 [NC,L,QSA]
    RewriteRule ^(image)/('d+)/('d+)/?$ $1.php?group_id=$2&img_id=$3 [NC,L,QSA]
    RewriteRule ^(poll|post)/('d+)/('d+)/?$ $1.php?group_id=$2&$1_id=$3 [NC,L,QSA]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?q=$1 [NC,L]
</IfModule>

使用 htaccess 不是一个好的选择,因为你有很多页面。

从长远来看,它是不可维护的。请使用任何路由模块(如 http://fatfreeframework.com/routing-engine)

另一个解决方案,通过向规则添加一些独特的路径,

example:
RewriteRule ^news/([^/]*)'.html$ /posts.php?id=$1 [L]
RewriteRule ^polls/([^/]*)'.html$ /polls.php?id=$1 [L]
result:
domain.com?posts.php?id=421 -> domain.com/news/421.html
domain.com?polls.php?id=17 -> domain.com/polls/17.html