douhandie6615 2018-07-05 20:35
浏览 33
已采纳

htaccess和php路由

I was learning today about Rewrite and PHP routing. I wrote the following .htaccess file:

    RewriteEngine On
    RewriteRule ^(.+)$ testing.php?url=$1 [NC,L]

The testing.php has the following code:

    <?php
       echo $_GET["url"];
    ?>

When I enter the following URL for example: http://localhost/tests/Hello The following is shown in the browser:

     testing.php

But I am expecting "Hello" to show instead of "testing.php". I tried to change NC to QSA and it worked successfully but why the first case is not working?

Thank you.

  • 写回答

2条回答 默认 最新

  • doukun8670 2018-07-05 20:57
    关注

    It's likely that the URL is being rewritten more than once.

    The first time rewrites /Hello to testing.php but then internally a separate request is made to testing.php and ran through the rewrite engine again. That will give you testing.php as the URL parameter.

    Using QSA means that on the second request it is appending to the query string as opposed to overwriting it. If you looked at $_SERVER['QUERY_STRING'] you would likely see something like url=testing.php&url=Hello (or similar) and php is just using the last value in url.

    Using NC is not necessary as the pattern you are using has no case (.+ matches one or more of any character regardless of case).

    Using L means to stop processing rules in this request, but doesn't stop processing rules in subsequent requests (including transparent/internal subsequent requests).

    Usually this is fixed by telling mod_rewrite to ignore the request if it is made to a file that exists using a RewriteCond like:

    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)$ testing.php?url=$1
    

    Which tells apache that if the requested filename is not a file and not a directory, process the rule. With this in place, the request to testing.php will see the file exists, condition fails and so the rule isn't processed additional times. Nothing would stop additional rules from applying though if they exist. And also, just an FYI, conds only apply to the very next rule. So if you multiple rules, you need these cond for each of them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀