【问题标题】:Remove multiple file extensions with .htaccess使用 .htaccess 删除多个文件扩展名
【发布时间】:2014-08-29 14:20:04
【问题描述】:

我有一个子域作为一个全新的网站 (subdomain.domain.com = subdomain.com)。我主要使用 .html 文件,但想摆脱那些扩展名(而不是 http://subdomain.com/file.html,我想要 http://subdomain.com/file )。我已使用下面的 .htaccess 代码来完成此操作。

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.html [L,QSA]

唯一的问题是,我还需要去掉网站上其他文件的 .php 扩展名。大多数人说用 .php 替换 .html 来复制上面的代码。我已经这样做了;不起作用。我已经尝试了许多其他版本的代码,但仍然无法正常工作。

由于我根本不是 .htaccess 方面的专家,谁能解释一下如何删除 .html 和 .php 文件扩展名? 提前致谢。

我不认为这是一个重复的问题,因为我还没有看到其他人问过如何一次替换多个文件扩展名。

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    你可以像这样使用重写规则:

    Options +FollowSymLinks
    RewriteEngine on
    
    # for adding .html extension if matching file exists
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1\.html -f [NC]
    RewriteRule ^(.+?)/?$ /$1.html [L]
    
    # for adding .php extension if matching file exists
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
    RewriteRule ^(.+?)/?$ /$1.php [L]
    

    【讨论】:

    • 感谢您的回答;它虽然抛出 404
    • 文件在主域文件夹(不是子域)。无论有什么其他规则,您的代码都会抛出 404 - 我将它们全部删除并尝试过......
    • 也可以RewriteRule ^(.+?)/?$ $1.html [L](或查看更新)
    • 无论你对 html 块所做的一切都有效。我对 php 块进行了这些更改,它可以工作。但它们不能同时工作——根据底部的代码块删除 html 扩展或 php 扩展(我认为?)
    • 在尝试了这里和网络上的大量示例代码和建议之后,您的代码是第一个/唯一一个可以工作的!谢谢你。 php 和 html 文件现在都可以在 URL 中没有扩展名。
    【解决方案2】:

    要删除多个文件扩展名,您可以在 /root/.htaccess 中使用以下规则。

    RewriteEngine on
    
    RewriteBase /
    #terminate all rewrite loops
    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteRule ^ - [L]
    #1)Remove ".html" , ".php",".css" extension.
    #The following rule redirects "/file.ext" to "/file" 
    RewriteRule ^(.+)\.(html|php|css)$ $1 [L,R,NE]
    #checks if "/file" .html exists, if it exits ,map "/file" to "/file.html"
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^(.*?)/?$ $1.html [L]
    #checks if "/file" .php exists, if it exits ,map "/file" to "/file.php"
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.*?)/?$ $1.php [L]
    #checks if "/file" .css exists, if it exits ,map "/file" to "/file.css"
    RewriteCond %{REQUEST_FILENAME}.css -f
    RewriteRule ^(.*?)/?$ $1.css [L]
    

    上述规则删除了 .php 、.html 和 .css 扩展名。要删除更多扩展,您可以根据需要编辑此 .htaccess。

    【讨论】:

      猜你喜欢
      • 2016-12-28
      • 2017-06-07
      • 2015-01-25
      • 2012-05-14
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多