【问题标题】:Multiple different php pages need to be friendly URL - url rewrite多个不同的php页面需要友好的URL - url rewrite
【发布时间】:2015-02-08 10:32:44
【问题描述】:

我的 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 重定向到每个页面及其参数。

【问题讨论】:

    标签: php .htaccess mod-rewrite url-rewriting


    【解决方案1】:

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

    <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>
    

    【讨论】:

      【解决方案2】:

      使用 htaccess 不是一个好的选择,因为您有这么多页面。

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

      【讨论】:

        【解决方案3】:

        通过向规则添加一些唯一路径的另一种解决方案,

        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
        

        【讨论】:

          猜你喜欢
          • 2015-12-10
          • 2013-02-06
          • 2011-09-23
          • 2016-01-13
          • 2019-04-30
          • 2011-02-05
          • 2010-12-31
          • 2011-07-31
          • 1970-01-01
          相关资源
          最近更新 更多