使用 Apache mod_rewrite 产生错误响应或 500 错误响应

Using Apache mod_rewrite produces incorect response or 500 error response

我正在尝试创建一个以这种方式工作的单页应用程序:

If the HTTP Request header Accept is set to application/json server service.php else server index.html

这是我当前的配置文件:

<Location "/" >

    RewriteEngine on

    # JSON response
    RewriteCond %{HTTP_ACCEPT} application/json [NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . service.php [L]

    # HTML Response
    RewriteCond %{HTTP_ACCEPT} !application/json [NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.html [L]

</Location>

我还需要处理 SPA 的路径 ("/")

我通过谷歌搜索尝试过的一些方法给出了 500/400 响应代码,我已经尝试了一整天浏览文档。

请检查我的配置并指出正确的方向。此外,如果可能的话,请简要说明 mod_rewrite 的工作原理。我正在使用 linux 电脑。

此代码应该适用于您的网站根目录 .htaccess:

RewriteEngine on

# ignore all files and directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# JSON response
RewriteCond %{HTTP_ACCEPT} application/json [NC]
RewriteRule . service.php [L]

# HTML Response
RewriteRule . index.html [L]

我这样写我的并将它放在 VertualHost 上下文中:

RewriteEngine on

# JSON
RewriteCond %{HTTP_ACCEPT} application/json [NC]
RewriteRule . /service.php [L]

# Everything else
# Note: for some reason, if the code below is not in Location directive, js & css are loaded with text/html MIME
<Location "/" >
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /index.html [L]
</Location>