通过 RewriteEngine 替换 URL 中的子字符串

Replace substring in URL via RewriteEngine

我拼命想让 RewriteEngine 重写以下模式:

https://example.com/api/model/id/
https://example.com/staging/api/model/id/

内部

https://example.com/index.php/model/id/
https://example.com/staging/index.php/model/id/

我已经尝试了几个委员会的一些建议,但 none 对我来说是可行的。 理想情况下,规则应该只搜索“/api/”并将其替换为“/index.php/”。我不明白为什么会这样很难做到这一点,我的其他规则到目前为止都很好...

这是我最后一次尝试:

RewriteEngine On
RewriteRule ^(.+)/api/(.+)$ /index.php/ [R=301,L]
# RewriteRule ^/api/(.*)$ /index.php/ [R=301,L,NC]
# RewriteRule ^(.+)/api/(.+)$ http://localhost/dev/someFolder/index.php/ [R=301,L]

我做错了什么?我只是告诉规则使 ($1)/api/($2) 变为 ($1)/index.php/($2),这不应该那么难。理想情况下,规则也不应该关心“/api/”模式之前的内容。

像这样...

RewriteEngine On
                
RewriteRule ^api/(.*)$ /index.php/ [NC]

RewriteRule ^staging/api/(.*)$ /staging/index.php/ [NC]

我找到了一个解决方法,在大多数用例中似乎都能正常工作:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) ./index.php/ [L]

在这里找到答案:htaccess remove index.php from url

请记住,您必须将文件放在以要替换“index.php”的字符串命名的子目录中(例如替换 /index.php/$1 与 /api/$1 你必须将所有文件放入名为 api).

的子目录中

这非常适合我的用例。