将 URL 从 .json 重写为 .php
我希望 http://server/path/app.json?a=foo&b=bar
映射到 http://server/path/foo.php?a=foo& b=bar
使用 mod_rewrite
。我的 .htaccess 中有以下咒语,它没有给出任何欢乐
RewriteEngine On
RewriteRule ^([^.?]+).json(.*)$ $1.php$2 [L]
建议?
更新:添加 rewrite.log 和 error.log 输出(注释不允许格式化)
我在 rewrite.log 中得到以下内容
strip per-dir prefix: /Users/user/Sites/dir/app.json -> app.json
applying pattern '^([^.?]+).json(.*)$' to uri 'app.json'
rewrite 'app.json' -> 'app.php'
add per-dir prefix: app.php -> /Users/user/Sites/dir/app.php
internal redirect with /Users/user/Sites/dir/app.php [INTERNAL REDIRECT]
,apache 服务器日志显示
The requested URL /Users/user/Sites/dir/app.php was not found on this server.
I want http://server/path/app.json?a=foo&b=bar
to map to http://server/path/foo.php?a=foo&b=bar
using mod_rewrite
. I have the following incantation in my .htaccess which doesn't give any joy
RewriteEngine On
RewriteRule ^([^.?]+).json(.*)$ $1.php$2 [L]
Suggestions?
Update: Adding rewrite.log and error.log output (comments don't allow formatting)
I get the following in the rewrite.log
strip per-dir prefix: /Users/user/Sites/dir/app.json -> app.json
applying pattern '^([^.?]+).json(.*)
and the apache server log says
The requested URL /Users/user/Sites/dir/app.php was not found on this server.
to uri 'app.json'
rewrite 'app.json' -> 'app.php'
add per-dir prefix: app.php -> /Users/user/Sites/dir/app.php
internal redirect with /Users/user/Sites/dir/app.php [INTERNAL REDIRECT]
and the apache server log says
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确地阅读了您的问题,您想要:
转到:
所以当您捕获
(app).json
$1
时,是app
和$2< /code> 是你的第二个括号,它什么都没有(
json
和?
之间的部分)。因为问号后面的所有内容都是查询字符串,无法在此处捕获。您的 rewriteRule 正在处理请求的文件,而不是查询字符串。所以你没有在任何地方捕获foo
。对于 QUERY_STRING,您可以在 rewriteRule 上使用[QSA]
标志,这样只需在重写后附加a=foo&b=bar
即可。在这里,您告诉 apache 重用
$1
(不带 .json 的文件名),因此app.json
将被重定向到app.php
,而不是 <代码>foo.php。将
app.json?a=b&z=r
重定向到app.php?a=b&z=r
。现在,如果您确实需要捕获
foo
作为第一个 QUERY_STRING 参数,则规则将变得更加困难。但你可以这样做(这里不是第一个参数,而是检测参数 'a=' 并在 %4 中捕获他的值):If I read your question correctly you want:
Going to:
Sowhen you capture
(app).json
$1
isapp
and$2
is your second parenthesis, it's ... nothing (the part betweenjson
and the?
). As everything after the question mark is the QUERY STRING and cannot be captured here. Your rewriteRule is working on the requested file, not on the QUERY STRING. So you didn't capturedfoo
anywhere. For the QUERY_STRING you could use the[QSA]
flag on the rewriteRule, that would simply appenda=foo&b=bar
after your rewrite.Here you tell apache to reuse
$1
(the filename without .json), soapp.json
will get redirected toapp.php
, notfoo.php
.Will redirect
app.json?a=b&z=r
toapp.php?a=b&z=r
.Now if you really need to capture
foo
as the first QUERY_STRING parameter the rule will become harder. But you could do it like that (here instead of the first parameter I detect the parameter 'a=' and capture his value in %4):