【问题标题】:Automatically Rewrite html,php,css or any file extension using htaccess?使用 htaccess 自动重写 html、php、css 或任何文件扩展名?
【发布时间】:2012-09-20 05:35:55
【问题描述】:

有没有办法自动从 url 中删除文件扩展名?

例如:

用户类型

www.website.com/page.html

它会自动将页面转换为:

www.website.com/page

如果可能的话,使用/:

www.website.com/page/

.htaccess 必须自动强制 url 重写文件扩展名。

【问题讨论】:

    标签: html regex .htaccess file-extension


    【解决方案1】:

    您尝试以错误的方式进行操作。您不想删除扩展名。您想要重写 对真实文件的无扩展名请求。所以如果用户输入

    http://foo.bar/file
    

    您的服务器将按要求提供服务

    http://foo.bar/file.html
    

    为此,您需要mod_rewrite(或等效项)并根据您的需要设置重写规则。相同的模块也用于使 URL 看起来更好,所以而不是

    http://foo.bar/script.php?id=34&smth=abc
    

    你可以拥有

    http://foo.bar/script/id/34/smth/abc
    

    甚至

    http://foo.bar/script/34/abc
    

    Read more on mod rewrite

    【讨论】:

    • 反之,如果用户使用 html 键入它会删除它吗?
    • 是的,您可以以任何方式重写。如果您出于任何目的确实需要按照说明进行操作,那么没有问题。但如果你想实现“漂亮的 URL”,那么按照我的方式做会减少问题
    【解决方案2】:

    我在 .htaccess 中使用它(index.php 正在处理页面):

    RewriteRule ^home/$ index.php?page=home
    // Result: http://domain.com/home/
    

    如果你想让它更有活力:

    RewriteRule ^(.*)/$ index.php?page=$1
    // Result: http://domain.com/any-page/
    

    有关请求页面时可能需要的更多数据:

    RewriteRule ^(.*)/(.*)/$ index.php?page=$1&id=$2
    // Result: http://domain.com/data-page/15/
    

    如果您只想获取没有索引部分的被调用页面:

    RewriteRule ^(.*)/$ $1.php
    

    要删除用户添加的扩展:

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteCond %{REQUEST_FILENAME}\.html -f
    

    【讨论】:

      【解决方案3】:

      你需要做两件事。首先,您需要将所有链接更改为不带扩展名的 URL,然后您需要创建一个 301 重定向,以将仍然可能具有带有扩展名的旧 URL 的浏览器和机器人重定向到新的漂亮 URL。这是一个新位置的服务器响应,它不是重写(这是一个仅在服务器上的内部 URI 重写)。

      RewriteEngine On
      RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /(.*)\.(html?|php)
      RewriteRule ^ /%2/ [L,R=301]
      

      这样当有人在浏览器中输入http://www.website.com/page.html 时,他们会被重定向到http://www.website.com/page/,并且新的 URL 将出现在浏览器的 URL 地址栏中。

      现在您需要做的第二件事是在内部将其返回更改为有效资源,因为/page/ 不存在,它将返回 404。

      # need these so we don't clobber legit requests, just pass them through
      RewriteCond %{REQUEST_FILENAME} -f [OR]
      RewriteCond %{REQUEST_FILENAME} -d
      RewriteRule ^ - [L]
      
      # now check the extensions
      RewriteCond %{REQUEST_URI} ^/(.*?)/?$
      RewriteCond %{DOCUMENT_ROOT}/%1.php -f
      RewriteRule ^ /%1.php [L]
      
      RewriteCond %{REQUEST_URI} ^/(.*?)/?$
      RewriteCond %{DOCUMENT_ROOT}/%1.html -f
      RewriteRule ^ /%1.html [L]
      
      RewriteCond %{REQUEST_URI} ^/(.*?)/?$
      RewriteCond %{DOCUMENT_ROOT}/%1.htm -f
      RewriteRule ^ /%1.htm [L]
      

      您只需将这些放在文档根目录的 htaccess 文件中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        • 2014-12-22
        • 1970-01-01
        • 2016-12-28
        • 2011-08-29
        相关资源
        最近更新 更多