如何使用 mod_rewrite 将 /foo-bar 重写为 foo-bar.html 但将 /foo/bar 重写为 foo-bar.html?
如何将 /foo-bar
重写为 foo-bar.html
但将 /foo/bar
重写为 foo--bar.html< /code> 使用 mod_rewrite?
换句话说,将请求 URI 中的所有斜杠替换为 --
,然后附加 .html
。
我编写了以下代码:
RewriteEngine On
RewriteBase /
# Take care of /foo/bar and /foo-foo/bar-bar
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/?$ $1--$2.html [L]
# Take care of /foo, or /foo-bar-baz-whatever-no-slashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-]+)/?$ $1.html [L]
这似乎在某些服务器上有效,但在我的服务器上似乎搞乱了重写:
在此服务器上找不到请求的 URL
/foo.html/bar
。
似乎太早附加 .html
了。
关于如何解决此问题以及导致其在该特定服务器上失败的任何想法?
How to rewrite /foo-bar
to foo-bar.html
but /foo/bar
to foo--bar.html
using mod_rewrite?
In other words, replace all slashes in the request URI with --
, then append .html
.
I wrote the following code:
RewriteEngine On
RewriteBase /
# Take care of /foo/bar and /foo-foo/bar-bar
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/?$ $1--$2.html [L]
# Take care of /foo, or /foo-bar-baz-whatever-no-slashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-]+)/?$ $1.html [L]
This seems to work on some servers but on mine it seems to mess up the rewrites:
The requested URL
/foo.html/bar
was not found on this server.
It seems to append the .html
too early.
Any ideas on how to fix this, and what is causing it to fail on this particular server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定为什么你的例子不起作用。提供您正在使用的 apache 版本会有很大帮助。 Apache/2.2.14,我能够复制该问题
如果您删除 RewriteBase 指令并使用
Apache/2.2.14
<代码>
RewriteEngine On
你应该有更好的运气。
将来请调高日志级别,以便更轻松地调试正在发生的情况。
I'm not sure why your example isn't working. Supplying the apache vesion you are using would help a lot. I was able to replicate the issue with Apache/2.2.14
If you remove the RewriteBase Directive and go with
Apache/2.2.14
RewriteEngine On
you should have better luck.
In the future look turn up your log level for easier debugging of what's going on.
发生这种情况的一种情况是
MultiViews
已启用,但AcceptPathInfo
设置为Off
(或Default
并且处理程序不接受路径信息),并且foo.html
存在。Apache 注意到您对
/foo/bar
的请求并未指向真实资源,并将其映射到/foo.html
,路径信息为/栏
。由于不允许使用路径信息,Apache 会为请求返回 404。同样,mod_rewrite
不会执行重写,因为/foo.html
现在是一个现有文件。这种情况的解决方案是关闭
.htaccess
文件中的MultiViews
:One case where this seems to happen is when
MultiViews
is enabled, butAcceptPathInfo
is set toOff
(orDefault
and the handler doesn't accept path info), andfoo.html
exists.Apache notices that your request for
/foo/bar
doesn't point to a real resource, and maps it to/foo.html
with the path info of/bar
. Because path info is not allowed, Apache returns a 404 for the request. Likewise,mod_rewrite
doesn't perform a rewrite because/foo.html
now is an existing file.The solution for this scenario would be to turn off
MultiViews
in your.htaccess
file: