很久之后,我终于弄明白了。事实证明,我做错了几件事(看图)。
我的第一个致命的谬误是我在.htaccess 文件中做生意,但我在这方面是错误的。我发现的第一个问题是.htaccess 文件是坏 并且应该避免,如果您可以将全局配置与<Directory "/var/www/html/..."></Directory> 语句结合使用,则应该完全忽略它。我犯的第二个错误(注意:我在发布上述问题后犯了这个错误)是 .htaccess 规则不适用于我假设的层次结构;恰恰相反,事实上。 .Htaccess 下级子目录中的配置文件实际上被其上级目录 kin 覆盖,而不是相反。
我的第二个错误实际上是我使用 RewriteRule 语句的方式。对于其他只是想与 Apache 相处,并且对学习其内部机制不感兴趣的人,请记住,通过阅读 documentation,您实际上可能会节省更多的时间。实际上,这对大多数事情都是如此。
可以在下面找到最终成功的代码。 (这是来自 /etc/apache2/sites-enabled/000-default.conf 文件,通过 SSH 连接通过 sudo nano 编辑)
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
<Directory "/var/www/html">
AllowOverride All
</Directory>
<Directory "/var/www/html/">
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !/api
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</Directory>
<Directory "/var/www/html/api/">
RewriteBase /api/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /api/api.php/$1 [L]
</Directory>
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
这会将所有不以/api/(例如/home 或/faq)开头的请求重定向到Angular 的index.html,并将任何API 请求(api/People/27 或/api/Customers)重定向到api.php 文件(位于/api/api.php)。
编辑:我偶然发现了上述代码的一个问题,即它没有将实际 URL 转发到 api.php 以使其发挥作用。这已通过匹配^(.*)$ 并使用$1 将答案与重定向规则联系起来得到纠正