【问题标题】:How to remove both the prefix and file extension from url in htaccess如何从htaccess中的url中删除前缀和文件扩展名
【发布时间】:2019-05-24 10:11:16
【问题描述】:

我目前有 htaccess 规则,它将所有网站流量重定向到没有任何前缀的 URL。比如:

www.mywebsite.com -> mywebsite.com

现在我想包含一个规则,该规则还从 URL 中去除 .html 扩展名,以便删除 URL 前缀、任何文件扩展名和“index.html”。比如:

www.mywebsite.com/index.html -> mywebsite.com

www.mywebsite.com/contact.html -> mywebsite.com/contact

我的代码如下:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

如何添加删除前缀、.html 扩展名和“index.html”的规则?

【问题讨论】:

  • 你想删除 www.从网站网址?和 .html 来自文件?
  • 是的,完全正确。例如:www.mywebsite.com/index.html -> mywebsite.com
  • 其实你自相矛盾。您使用index.html 给出的示例not 仅删除了“.html”文件扩展名...
  • 啊,我应该更清楚。我想删除前缀和 .html 扩展名,正如我在示例中显示的那样

标签: .htaccess redirect


【解决方案1】:
  1. 从域 URL 中删除 WWW 前缀

      RewriteEngine on
      RewriteCond %{HTTP_HOST} ^www\.
      RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
    
  2. 要删除 .html 扩展名,请使用:

    #remove html file extension-e.g. https://example.com/file.html will become https://example.com/file
    RewriteEngine on 
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.html -f
    RewriteRule ^(.*)$ $1.html [NC,L]
    
  3. 删除 index.html

    RewriteEngine On
    RewriteRule ^index\.html$ / [R=301,L]
    RewriteRule ^(.*)/index\.html$ /$1/ [R=301,L]
    

【讨论】:

  • 我应该更清楚。如示例中所示,我想同时删除前缀和 .html 扩展名。因此,一组规则可以做到这一点:www.mywebsite.com/index.html -> mywebsite.com
  • 感谢您的更新。现在唯一的事情是这 3 个单独的集合需要组合成 1 组规则,我可以放入我的 htaccess 文件中。有这样的可能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2022-01-21
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多