linux - 使用 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计算机。
解决方案
此代码应该在您的站点根目录 .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>
推荐阅读
- sql-server - SQL 触发器 - 分配金额
- mysql - MySQL GROUP BY 按天查询组结果
- c# - 如何将收集的 API 数据中的单个变量发送到另一个位置
- python - 是否有任何方法可以将 html 文本转换为 xhtml?
- kotlin - 将字段名称作为输入的 Corda 自定义查询
- apache-flink - 如何在开始时间和结束时间之间请求 Flink 作业指标?
- ruby-on-rails - sprockets 需要 Ruby 版本 >= 2.5.0 on rails 5
- php - PHP max 同时脚本调用...(调度程序?)不是 CRON
- c# - 如何使用 System.Text.Json 库在现有 json 中添加属性?
- django - 未登录时 Django 中间件扩展 self.request 错误