永久重定向删除URL中的文件扩展名

时间:2018-08-04 22:30:49

标签: apache mod-rewrite

当使用以.html结尾的URL访问页面时,我希望将该URL更改为没有扩展名,并永久重定向报告301。我有严重的困难。在阅读了许多文档和教程,并在堆栈溢出中搜索了数小时之后,我得到的最接近的结果与此相反(没有扩展名的URL添加了一个):

<Location />
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME}\.html -f
 RewriteCond %{REQUEST_URI} !/$
 RewriteCond %{REQUEST_URI} !\.html$
 RewriteRule ^(.*)$ https://%{HTTP:Host}%{REQUEST_URI}.html [L,R=permanent]
</Location>

1 个答案:

答案 0 :(得分:0)

这可以分两个步骤完成,使用REDIRECT_LOOP环境变量来防止循环,使用目录部分中针对Web根目录(或Web根目录中的.htaccess)的指令,以便可以使用RewriteRule中的匹配字符串进行永久重定向。

<Directory "/var/www/html">

 RewriteEngine On

 RewriteCond %{REQUEST_FILENAME} !-d # if the request is not a directory
 RewriteCond %{REQUEST_FILENAME} !-f # if the request is not a file
 RewriteCond %{REQUEST_FILENAME}\.html -f # if adding .html it is a file
 RewriteCond %{REQUEST_URI} !\.html$ # if the request doesn't end in .html
 RewriteCond %{REQUEST_URI} !/$ # if the request doesn't end in /
 RewriteRule ^(.*)$ $1.html [L,E=LOOP:1] # then return the request as if it ended with .html and set the loop variable

 RewriteCond %{ENV:REDIRECT_LOOP} !1 # if we didn't just added .html
 RewriteRule ^(.*)\.html$ https://%{HTTP:Host}/$1 [L,R=permanent] # then 301 redirect the request to the request without the .html

</Directory>

这样可以做到,如果您有example.htmlexample/index.html,那么将永远不会加载example.html