如何.htaccess伪静态+隐藏扩展



为什么我不能使用以下内容?

RewriteRule ^(.*)$ $1.html [L]

.htaccess文件:

RewriteRule ^(.*)$ index.php [L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ $1.html [L]
RewriteRule ^(.*)$ index.php [L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ $1.html [L]

第一条规则将所有重写为index.php。随后的指令实际上被忽略了。

然而,第二条规则也重写了所有(相同的模式^(.*)$-明显的冲突(,它不映射到现有文件或目录以附加.html扩展名。第二条规则的限制性更强。

看来你想做的是:

  1. .html扩展名附加到将映射到.html文件的URL
  2. 将(我认为(未映射到物理文件和目录的所有其他请求重写到index.php

附加假设

  • .htaccess文件位于文档根目录中
  • 应映射到.html文件的请求URL在URL路径中不包含点。因此,URL路径中的点仅表示文件扩展名
  • 如果你真的把everything重写为index.php(就像你所做的那样(,那么它也会重写你所有的静态资源(CSS、JS、图像等(,所以我假设你想对静态资源和任何其他会映射到文件或目录的东西进行例外处理

请尝试以下操作:

RewriteEngine On
# Append the ".html" extension if the target file exists
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^([^.])$ $1.html [L]
# Rewrite other requests that don't map to files/directories to index.php
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule !.(?:css|js|jpg|png|gif)$ index.php [L]

最新更新