在 Apache HTTPD 2.2 中,我想要使对/index.foo
或 的请求/foo
(如果它们不是文件或目录)变为/index.php?transform=foo
,无论 URL 有多少级。
成功的标准是:
http://www.site.example/index.foo
->http://www.site.example/index.php?transform=foo
http://www.site.example/foo
->http://www.site.example/index.php?transform=foo
http://www.site.example/bar/baz/foo
->http://www.site.example/bar/baz/index.php?transform=foo
即,我不希望重写与 .htaccess 目录相关;我希望它们与请求中的最顶层目录相关。
答案1
# Check if file exists
RewriteCond %{REQUEST_FILENAME} ! -f
# Rewrite the URI if file doesn't exist and contains "index."
RewriteRule ^(.*)(index\.[^/]+)$ $1/index.php?transform=$2 [L]
# The same thing for any other URI
RewriteCond %{REQUEST_FILENAME} ! -f
RewriteRule ^(.*)([^/]+)$ $1/index.php?transform=$2 [L]
答案2
使用两个修改后的正则表达式版本解决了这个问题这一页:
# $1 = directory, $2 = extension
# Matches:
# - /html
# - /web/portfolio/html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*/)?(html|rss|txt)$ $1index.php?transform=$2 [L]
# $1 = directory, $2 = "index.", $3 = extension
# Matches:
# - /index.html
# - /web/portfolio/index.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*/)?(?:$|(index\.)(?:([^.]*$)|$))$ $1$2php?transform=$3 [L]