【问题标题】:Apache2 internal rewrite from sub domain to sub directoryApache2内部从子域重写到子目录
【发布时间】:2023-03-23 09:03:02
【问题描述】:

我正在尝试在内部重写(而不是重定向)从 api.domain.netdomain.net/api 的所有流量。

我有一个 VHost 处理domain.net。该端点支持 /api 子目录作为 API 的入口点。

我想设置另一个端点api.domain.net,最好在另一个可以处理 API 流量的 VHost 中。在这种情况下,我不想使用/api 子目录,因为域意味着这是一个 API。

我的项目已经使用.htaccess 将所有流量重写为index.php,因为所有请求都由PHP 路由。规则:RewriteRule ^(.*)$ /index.php [L,END]

理想情况下,我想将新的 API 重写规则添加到 VHost 配置中,因为 API 和非 API 客户端的代码(和 .htaccess)应该相同。

解决这个问题的最佳方法是什么?

我试图在.htaccess 中添加一个规则(在index.php 规则之前),只是为了测试:RewriteRule ^(.*)$ /api/$1,但由于某种原因它没有做任何事情。 添加后,我期望所有流量,例如:https://local.domain.net/api_method 将被 PHP 视为源自 https://local.domain.net/api/api_method,因此路由正确。

编辑。 .htaccess 看起来像这样(剥离了不相关的东西):

RewriteEngine on
# Allow the Let's Encrypt cert verification
RewriteRule ^.well-known/ - [L,NC]
Options +FollowSymlinks

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

RewriteRule ^build/js/.*\.js$ - [NC,L]

# Run all non-file-asset requests through site entry point
RewriteCond %{REQUEST_URI} !^/resources/frontend/(images|swf|ttf) [NC]
RewriteRule ^(.*)$ /index.php [L,END]

【问题讨论】:

  • 如果您为此使用专用的 VHost,那么为什么首先要费心重写 - 而不是一开始就将其 DocumentRoot 设置为正确的文件夹?
  • 这是因为DocumentRoot 是一样的。应用程序入口点完全相同。
  • 那么/api 不是一个实际的目录,而只是一个编造的路径?
  • @Cbroe 确实是路线。上面的规则之一是将所有路由重写为index.php,以便应用程序可以处理路由。
  • 您能否展示完整的重写设置(至少与此相关的部分)?如果您在api.domain.net vhost 内部重写为/api/$1,那么我认为再次将其重写为某个 index.php 的任务也必须在那里发生。如果您现在只设置重写domain.net 的请求,那么在不同的虚拟主机下进行内部重写将永远无法实现。

标签: php apache .htaccess vhosts


【解决方案1】:
<VirtualHost *>
  ServerName api.example.com
  Options +FollowSymLinks
  RewriteEngine On
  RewriteCond %{REQUEST_URI}/ api
  RewriteRule ^(.*) http://www.example.com/%{REQUEST_URI} [R=301,NC]
</VirtualHost>

应该这样做

【讨论】:

  • 没错,API 使用者不应该看到重定向。
  • [R=301,P,NC]替换[R=301,NC]
  • 等待被误解了,我会在 20 分钟内更新答案,对此感到抱歉
猜你喜欢
  • 2014-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
  • 2014-04-10
  • 1970-01-01
相关资源
最近更新 更多