如何使用mod_rewrite将/ foo-bar重写为foo-bar.html但/ foo / bar重写为foo-bar.html?

时间:2010-09-07 16:56:59

标签: 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_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]

这似乎适用于某些服务器,但在我看来它似乎弄乱了重写:

  

在此服务器上找不到请求的网址/foo.html/bar

似乎过早追加.html

有关如何解决此问题的任何想法,以及导致它在此特定服务器上失败的原因?

2 个答案:

答案 0 :(得分:1)

我不确定为什么你的例子不起作用。提供你正在使用的apache vesion会有很大帮助。我能够用Apache / 2.2.14

复制这个问题

如果您删除了RewriteBase指令并继续使用 阿帕奇/ 2.2.14

RewriteEngine On

# 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]

# 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]

你应该有更好的运气。

将来,请查看日志级别,以便更轻松地调试正在进行的操作。

答案 1 :(得分:1)

似乎发生这种情况的一种情况是启用MultiViews时,AcceptPathInfo设置为Off(或Default且处理程序不接受路径信息),foo.html存在。

Apache注意到您对/foo/bar的请求未指向真实资源,并将其映射到/foo.html,路径信息为/bar。由于不允许路径信息,Apache会为请求返回404。同样,mod_rewrite不执行重写,因为/foo.html现在是现有文件。

此方案的解决方案是关闭MultiViews文件中的.htaccess

Options -MultiViews