首页 > 解决方案 > 使用 Apache mod_rewrite 会产生不正确的响应或 500 错误响应

问题描述

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

如果 HTTP 请求标头Accept设置为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计算机。

标签: linuxapachesingle-page-application

解决方案


此代码应该在您的站点根目录 .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>

推荐阅读