apache - .htaccess 删除 .html 并强制重定向到无扩展名的 url

标签 apache .htaccess mod-rewrite redirect url-rewriting

我正在尝试从 URL 中删除 .html 扩展名,并将 302 重定向到无扩展名 URL,如下所示:

http://example.com/file.html -> http://example.com/file

我看过很多 stackoverflow 答案,尝试过,但不幸的是没有成功。我提出了这个,但我不明白为什么它不起作用:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteCond %{REQUEST_URI} \.html$
RewriteRule (.*)\.html$ /$1 [R=302,L]  

RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteCond %{REQUEST_URI} !\.html$ [NC]
RewriteRule ^(.*)$ $1.html

第一个 block 应重定向到无扩展版本,第二个 block 应找到该文件。

最佳答案

这里需要使用 %{THE_REQUEST} 来防止重写循环错误。否则,如果没有 THE_REQUEST 变量,规则将继续重写 file => file.html=>file=>file.html..

RewriteEngine On

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule (.*) /%1 [R=302,L]  

RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

关于apache - .htaccess 删除 .html 并强制重定向到无扩展名的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34295302/

相关文章:

django - 限制通过 apache 访问 django 管理站点

apache - 如何确定运行 Apache 的用户身份?

php - 当我们从移动.htaccess 访问时如何更改根路径?

http - 使用 mod_rewrite 后找不到图像

linux - centos无法重启apache

php - 使用 .htaccess 重写 URL 使重复的 mysql 条目

wordpress - 301 将旧的 WordPress 网址重定向到新的 cakephp 网址

regex - mod_rewrite 将 '_' 替换为 '-'

php - 使用 htaccess 获得良好的 SEO 链接

apache - 如何为 apache 做贡献?