如何使用 Apache mod_rewrite 隐藏 .html 扩展名 [英] How to hide the .html extension with Apache mod_rewrite
问题描述
我有少量静态网站,我只想隐藏 .html 扩展名:
I have a small number of static sites where I simply want to hide the .html extension:
- url
/foo
获取静态文件/foo.html
- 浏览器仍然显示url
/foo
- the url
/foo
fetches the static file/foo.html
- the browser still displays the url
/foo
然后客户端可以以 mydomain.com/foo
而不是 mydomain.com/foo.html
样式发送书签.
The client can then send out bookmarks in the style mydomain.com/foo
rather than mydomain.com/foo.html
.
这听起来很简单,我以前很喜欢使用 mod_rewrite
(比如使用 WordPress 或重定向),但事实证明,这比我想象的更难破解.也许我遗漏了一些非常明显的东西,但我在任何地方都找不到解决方案,而且我已经研究了一整天!
It sounds very simple, and I've used mod_rewrite
happily before (say with WordPress or for redirects), but this is proving much harder to crack that I thought. Perhaps I'm missing something really obvious, but I can't find a solution anywhere and I've been at it all day!
我们运行自己的服务器,所以它可以去任何最好的地方.
We run our own server, so this can go wherever is the best place.
附录
下面检查的解决方案工作正常.然后在运行该网站一段时间后,我注意到两个问题:
The solution checked below worked fine. Then after running the site awhile I noticed two problems:
所有页面都开始没有样式了.我重新加载,清除缓存等,但仍然没有风格.我以前也遇到过这个问题,找不到来源.
all pages began to appear unstyled. I reloaded, cleared the cache, etc., but still no-style. I've had this trouble before, and can't locate the source.
有一个目录和一个名为gallery"的 html 文件,因此/gallery 链接显示的是目录列表而不是 html 文件.我应该能够对那个进行排序,但欢迎提供更多提示:-)
There's a directory AND an html file named 'gallery', so the /gallery link shows a directory listing instead of the html file. I should be able to sort that one, but further tips welcome :-)
推荐答案
试试这个规则:
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [L]
这将在附加 .html
时重写所有可以映射到现有文件的请求.
This will rewrite all requests that can be mapped to an existing file when appending a .html
.
这篇关于如何使用 Apache mod_rewrite 隐藏 .html 扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!