php - 配置 htaccess 以使用 Angular 和 PHP 路由

标签 php angular .htaccess mod-rewrite

我正在尝试使用 Angular 4 和 PHP 路由,但我无法配置它以便同时使用两者。我可以让它与其中之一一起工作,但不能同时与两者一起工作。

这是我的文件夹结构:

root
│ index.html
│ vendor.bundle.js    
| [..other angular files..]  
│
└─api
│  │ index.php
│  │ init.php
│  │
│  └─vendor
└─assets
└─[..other project files..]

在文件 api/index.php 上,我设置 PHP 路由。


所以,当我使用这个.htaccess时,PHP路由按预期工作,但是当我刷新页面时,Angular路由不起作用,因为它认为作为 PHP 路由。

<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . api/index.php [L]

    RewriteBase /
    RewriteRule ^index.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

我尝试将 .htaccess 更改为仅当被调用的 URL 包含路由 /api/ 时才进行重定向,但它不起作用。像这样:

<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REQUEST_URI} api
    RewriteRule . api/index.php [L]

    RewriteBase /
    RewriteRule ^index.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

使用此代码,即使我刷新页面,Angular 路由也能正常工作,但 PHP 路由永远不会重定向到 index.php 文件,因此它始终返回 null。

我需要做什么来解决这个问题?

最佳答案

由于我对 htaccess 不太了解,所以我不知道这个答案是否 100% 正确,但我设法让它发挥作用。

我所做的是将 RewriteBase/ 行移至顶部,并删除 RewriteRule ^index.html..,最后添加 .htaccess 看起来像这样:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} api
RewriteRule . api/index.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>

现在它正在按预期工作。如果有人有更好的答案,我将保留这个问题。

关于php - 配置 htaccess 以使用 Angular 和 PHP 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46005914/

相关文章:

php - 自动按计划打印 pdf

javascript - Angular2 从数组创建列表

jquery - 使用带 angular4 的灯光 slider

php - Apache Mod 重写对我不起作用 当在 url 中使用 (-) 时?

php - 关于 PHP 语法错误的 Apache 内部错误 500 (htaccess)

php - MDM DeviceLock 负载错误

php - WampServer HTTP 403 禁止

php - 使用 PHP 和 Linux 获取文本 : can't switch languages

css - 无法使表单控件透明

apache - 使用 .htaccess 通过 index.php 重新路由所有请求,除了特定的一组请求