doushang9172 2018-02-15 20:30
浏览 48
已采纳

.htaccess使用无限参数重写规则

I'm having trouble racking my brain around how to create a RewriteRule in .htaccess to accept unlimited perameters for friendly URLs. Right now, my .htaccess file looks like this:

RewriteRule "^category/([a-z0-9-]+)/?$" "category.php?cat1=$1" [NC,L]
RewriteRule "^category/([a-z0-9-]+)/([a-z0-9-]+)/?$" "category.php?cat1=$1&cat2=$2" [NC,L]
RewriteRule "^category/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/?$" "category.php?cat1=$1&cat2=$2&cat3=$3" [NC,L]

I have this same line repeated about 10 times to accept 10 different categories. Is there an easier way to accomplish this? Thanks in advance for the help!

  • 写回答

1条回答 默认 最新

  • dongshi1934 2018-02-15 21:13
    关注

    This is not a direct answer to your question, here is an alternative to using RewriteRule and .htaccess (Which IMO are more a optimal way to achieve what you want).

    Firstly, if at all possible you should favor using your apache server config files over a .htaccess file. There are performance problems as well as potential secuirty problems that arrise from using .htaccess. This is well documented on the internet, so I wont repeat it here, but a quick google search should provide more information.

    Secondly, instead of using RewriteRule, a much more scalable solution is to use FallbackResource and a router file.

    The idea is if there is ever a request to your site which does not match any of the existing files, the request will be handled by your FallbackResource file.

    If in your config (or htaccess) you have

    FallbackResource router.php
    

    and someone makes a request for example.com/category/potato the request will cause the server to serve router.php (this is assuming category/potato is not actually a file on your server)

    So what goes in router.php? Well you cannot serve every request the same page of course, so you inspect the details of the request that was made and then serve the correct content accordingly.

    a very simple (and untested) router:

    $request_uri = $_SERVER['REQUEST_URI']; // eg /category/potato
    
    $path_tokens = explode("/", trim($request_uri, "/"));
    
    if($path_tokens[0] == "category"){
        $category = $path_tokens[1];
        renderCategoryPage($category); // can render the category page for potatoes
    }
    

    This example is just to give you an idea, you will have to design and implement your own, but hopefully you can see how this gives more freedom that some britle rewrite rules.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?