apache - 永久重定向删除 URL 中的文件扩展名
问题描述
当使用以 .html 结尾的 URL 访问页面时,我希望 URL 更改为没有扩展名并报告 301 永久重定向。我遇到了严重的困难。在阅读了大量文档和教程,并在 Stack Overflow 上搜索了几个小时后,我得到的最接近的结果是相反的(没有添加扩展名的 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>
解决方案
这可以分两步完成,使用 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.html
然后永远不会被加载example/index.html
。example.html
推荐阅读
- reactjs - 如何在 netlify 应用程序中做出维护模式的反应
- r - 重新创建数据框以使用 for-loop
- python - 几天后 Ubuntu 21.04 nohup python 无限循环停止
- sql - 在 SQL 中生成组合
- android-emulator - 如何在 android studio 中更改 AVD android 模拟器信息?
- ruby-on-rails - 在一天中获得几个小时的 Rails 方式?
- reactjs - 如何将道具传递给 DrawerItem 组件?
- python - 使用 pyspark 对数据框中的数据进行聚类
- django - 如何为 django 项目设置可选的演示数据
- mysql - MySQL简单但慢的查询