代码之家  ›  专栏  ›  技术社区  ›  snehoozle

获取php中的浏览器url以获取重写的url

  •  1
  • snehoozle  · 技术社区  · 10 年前

    我已经编写了一个使用以下apachemod重写规则的restful api:

    <IfModule mod_rewrite.c>
    RewriteEngine on 
    RewriteBase /api
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ https://example.com/api/index.php?request=$1 [L]
    </IfModule>
    

    然而,在控制器中,我发现我无法正确获取查询字符串。

    当我在向 https://example.com/api/search/article?mh=7 :(1)

    $_SERVER['QUERY_STRING'] 
    

    我得到了以下结果:

    request=search/article
    

    当我尝试以下操作时:(2)

    $_SERVER['REQUEST_URI']
    

    我得到了以下结果:

    /api/index.php?request=search/article
    

    如何正确使用mod重写,并在api控制器中成功获取查询字符串?

    注意:示例的实际url已更改。

    1 回复  |  直到 10 年前
        1
  •  1
  •   Justin Iurman    10 年前

    假设你的htaccess在 /api/ 文件夹,应该是这样的

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

    注意:不要使用 http:// 否则将是外部重定向。此外,使用 QSA 从初始url附加查询字符串的标志。

    从您的示例中: https://example.com/api/search/article?mh=7 将被改写为 /api/index.php?request=search/article&mh=7


    编辑:如果你想要每个 http 要重定向到的API的url https 相等的

    <IfModule mod_rewrite.c>
    RewriteEngine on 
    RewriteBase /api/
    
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/api/$1 [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?request=$1 [L,QSA]
    </IfModule>