Apache 如何使用mod_rewrite将/foo-bar重写为foo-bar.html,而将/foo/bar重写为foo-bar.html?
如何使用mod_rewrite将Apache 如何使用mod_rewrite将/foo-bar重写为foo-bar.html,而将/foo/bar重写为foo-bar.html?,apache,url,mod-rewrite,url-rewriting,rewrite,Apache,Url,Mod Rewrite,Url Rewriting,Rewrite,如何使用mod_rewrite将/foo-bar重写为foo-bar.html,而将/foo/bar重写为foo--bar.html 换句话说,将请求URI中的所有斜杠替换为--,然后追加.html 我编写了以下代码: RewriteEngine On RewriteBase / # Take care of /foo/bar and /foo-foo/bar-bar RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILEN
/foo-bar
重写为foo-bar.html
,而将/foo/bar
重写为foo--bar.html
换句话说,将请求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
关于如何修复此问题,以及是什么原因导致此特定服务器出现故障,有什么想法吗?我不确定您的示例为什么不起作用。提供您正在使用的ApacheVesion会有很大帮助。我能够用Apache/2.2.14复制这个问题 如果删除RewriteBase指令并使用 Apache/2.2.14
重新启动发动机
# 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]
你应该有更好的运气
在将来,请提高日志级别,以便更轻松地调试正在发生的事情
#don't leave this on in production
RewriteLog "/private/var/log/apache2/rewrite.log"
RewriteLogLevel 5
出现这种情况的一种情况是启用,但设置为
Off
(或Default
,并且处理程序不接受路径信息),并且存在foo.html
Apache注意到您对/foo/bar
的请求没有指向真正的资源,并将其映射到路径信息为/bar
的/foo.html
。由于不允许使用路径信息,Apache将为请求返回404。同样地,mod_rewrite
不会执行重写,因为/foo.html
现在是一个现有文件
此方案的解决方案是在.htaccess
文件中关闭多视图
:
Options -MultiViews
奇怪的是,它似乎在没有
RewriteBase
指令的情况下工作。有什么线索吗?谢谢