这是我的配置:
- http://domain.com(显然是虚构的名称...)托管在运行 Apache 且启用了 mod_rewrite 的服务器上
- 名为“foo”的文件夹:(位于http://domain.com/foo/并且我想在其中放置我的 .htaccess 文件)仅包含 3 种类型的文件 .php、.htm、.html
- .php 文件(为了示例,我将引用其中之一:phpfile.php)
- .htm 文件(为了示例,我将引用其中之一:htmfile.htm)
- .html 文件(为了示例,我将引用其中之一:htmlfile.html)
- 在 foo 文件夹中,没有文件具有另一个扩展名或没有扩展名的等价文件(例如,foo 中既不存在 phpfile.htm 也不存在 phpfile.html 也不存在 phpfile,只有 php.file.php 存在)
这是我想要实现的目标:
- 在浏览器的地址栏中输入http://domain.com/foo/phpfile.php或http://domain.com/foo/htmfile.htm或http://domain.com/foo/htmlfile.html并点击“进入”:
- 我使用 301 重定向到http://domain.com/foo/phpfile或http://domain.com/foo/htmfile或http://domain.com/foo/htmlfile(取决于我拥有的文件选择),也就是说后者是现在显示在地址栏中的URL
- 在浏览器的地址栏中输入http://domain.com/foo/phpfile或http://domain.com/foo/htmfile或http://domain.com/foo/htmlfile并按“Enter”时:
- 我没有被重定向,地址栏中没有任何变化,而是服务器只为我提供 phpfile.php 或 htmfile.htm 或 htmlfile.html,具体取决于我请求的是哪一个
我一直在努力,到目前为止,我已经为我的 .htaccess 文件(位于“foo”文件夹中)提供了这个内容,不幸的是,它只适用于我感兴趣的两种情况中的最后一种(即当我请求“phpfile”时服务“phpfile.php”,当我请求“htmfile”时服务“htmfile.htm”或当我请求“htmlfile”时服务“htmlfile.html”),并且忽略301重定向:
Options +FollowSymLinks
RewriteEngine on
RewriteBase /foo
# Redirect permanently the requests for existing .php files
# to extensionless files (non present on the server)
# so that phpfile.php gets redirected to phpfile
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} \.php$
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule (.*)\.php$ $1 [R=301,NC]
# Redirect permanently the requests for existing .htm(l) files
# to extensionless files (non present on the server)
# so that htmfile.htm gets redirected to htmfile
# so that htmlfile.html gets redirected to htmlfile
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} \.html?$
RewriteCond %{REQUEST_FILENAME}\.html? -f
RewriteRule (.*)\.html?$ $1 [R=301,NC]
# Matching requests for non existing extensionless files
# with their existing equivalent on the server
# so that domain.com/foo/phpfile will display
# the contents of domain.com/foo/phpfile.php,
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule (.*)$ $1.php [L]
# so that domain.com/foo/htmlfile will display
# the contents of domain.com/foo/htmlfile.html,
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule (.*)$ $1.html [L]
# so that domain.com/foo/htmfile will display
# the contents of domain.com/foo/htmfile.htm,
RewriteCond %{REQUEST_FILENAME}\.htm -f
RewriteRule (.*)$ $1.htm [L]
提前感谢您的任何帮助/建议。