【问题标题】:How to use mod-rewrite to redirect API calls and web app calls accordingly如何使用 mod-rewrite 相应地重定向 API 调用和 Web 应用程序调用
【发布时间】:2019-07-31 06:55:40
【问题描述】:

我正在使用 php 构建一个应用程序,该应用程序提供 API 接口和 Web 应用程序 (HTML) 接口。我的文档根目录中的目录中都有这两个: /www/sys/api/www/sys/webapp 在每个目录中,我都有一个应该处理路由的路由器

/www/sys/api/public/api-index.php

/www/sys/webapp/public/webapp-index.php

现在我想做的是在我的/www/sys/ 中使用 .htaccess 文件以/www/sys/api/smth/smth/smth 的形式将任何请求路由到/www/sys/api/public/api-index.php?path=smth/smth/smth 和任何其他请求(www/sys/api 以外的任何请求,例如@ 987654328@ 或只是/www/sys/) 到/www/sys/webapp/public/webapp-index.php?path=smth

现在我有这个:

RewriteEngine On

RewriteRule ^api/(.+)$ api/public/api-index.php?url=$1 [L]

RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_URI} !^api/public/api-index.php
RewriteRule ^(.+)$ webapp/public/webapp-index.php?url=$1 [L]

这在某种程度上是有效的,除了:

  1. 转到 server/sys/api/ 将我发送到 server/sys/webapp/public/webapp-index.php 但如果我再添加一层 server/sys/api/hhh 就可以了!

  2. 如果我被重定向到 webapp,我没有得到完整的 url 参数,我总是得到 webapp/public/webapp-index.php,而在 API 中,我总是得到 public/api-inedx.php

总之,我需要获取此 .htaccess 以将 /sys/api/ 重定向到 /sys/api/api-index.php 并正确获取实际 url。提前致谢

【问题讨论】:

    标签: php apache routing


    【解决方案1】:

    经过大量调整后,我找到了一个解决方案,如果有人偶然发现这个问题,只需将其发布在这里 - 将 api-index.php 和 webapp-index.php 重命名为 index.php 现在只是去 /sys/api/ 或 /sys/webapp/ 不会导致无处可去! - 在每个公共目录的 htaccess 文件中发送路径参数 所以这是结构:

    sys
        api
            public
                 index.php
                 .htaccess [2]
        webapp
            public
                 index.php
                 .htaccess [3]
        .htaccess [1]
    

    [1]:

    RewriteEngine On
    
    RewriteRule ^api/(.*) api/public/$1 [L]
    
    RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
    
    RewriteRule ^(.*)$ webapp/public/$1 [L]
    

    [2] 和 [3]:

    Options -MultiViews
    
    RewriteEngine On
    
    Options -Indexes
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    
    RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多