.htaccess 重写 - 删除所有扩展名
.htaccess rewrite - remove all extensions
我想做一个删除所有扩展名的重写规则 - 无论文件名如何
https://example.com/filename.extension
-> https://example.com/filename
例如:
https://example.com/horses.txt
-> https://example.com/horses
https://example.com/icecream.json
-> https://example.com/icecream
我试过:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)\.*$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ *? [QSA,L]
</IfModule>
没有正常工作
你只能合理地做你要求的 MultiViews
。
例如,简单如:
Options +MultiViews
您需要删除现有的 mod_rewrite 指令。
现在,对 example.com/horses
的请求将被正确路由到 /horses.txt
或您正在使用的任何文件扩展名。 MultiViews
使用 mod_negotiation.
这对 mod_rewrite 来说并不容易,因为您需要依次测试每个文件扩展名,以便找出您需要重写回哪个文件,以便正确路由请求.例如。 example.com/horses
的请求应该路由到 /horses.txt
还是 horses.jpg
? MultiViews 为您做这个比较。
I would like a to do a rewrite rule that removes all extensions
尽管如此,您实际上需要删除 HTML 源中的文件扩展名。这不是你在 .htaccess
中做的事情,除非你需要保留 SEO 或已经链接回旧 URL 的反向链接。
UPDATE: Perhaps I wasn't clear enough, I would like the url to display without the extension even if it is linked to it, or to go to that file if linked without the extension
好吧,您实际上需要删除所有内部链接上的文件扩展名。您可以在 .htaccess
中发出 "redirect" 以删除扩展名,以便搜索引擎和第三方链接 - 但如果您的内部链接依赖于此,那么它可能会减慢用户和您的网站的速度,因为您正在使访问服务器的请求数量翻倍。
要删除直接请求(SEO/第三方链接)的文件扩展名,您可以这样做:
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^([^.]+)\.[\w]{2,4}$ / [R=302,L]
这确实假定 URL 路径中唯一的点是分隔文件扩展名的点。
困难的部分是在内部将请求重写回基础文件 并带有 扩展名 - 这就是 MultiViews
的用武之地(我的回答的第一部分)。
我想做一个删除所有扩展名的重写规则 - 无论文件名如何
https://example.com/filename.extension
->https://example.com/filename
例如:
https://example.com/horses.txt
->https://example.com/horses
https://example.com/icecream.json
->https://example.com/icecream
我试过:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)\.*$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ *? [QSA,L]
</IfModule>
没有正常工作
你只能合理地做你要求的 MultiViews
。
例如,简单如:
Options +MultiViews
您需要删除现有的 mod_rewrite 指令。
现在,对 example.com/horses
的请求将被正确路由到 /horses.txt
或您正在使用的任何文件扩展名。 MultiViews
使用 mod_negotiation.
这对 mod_rewrite 来说并不容易,因为您需要依次测试每个文件扩展名,以便找出您需要重写回哪个文件,以便正确路由请求.例如。 example.com/horses
的请求应该路由到 /horses.txt
还是 horses.jpg
? MultiViews 为您做这个比较。
I would like a to do a rewrite rule that removes all extensions
尽管如此,您实际上需要删除 HTML 源中的文件扩展名。这不是你在 .htaccess
中做的事情,除非你需要保留 SEO 或已经链接回旧 URL 的反向链接。
UPDATE: Perhaps I wasn't clear enough, I would like the url to display without the extension even if it is linked to it, or to go to that file if linked without the extension
好吧,您实际上需要删除所有内部链接上的文件扩展名。您可以在 .htaccess
中发出 "redirect" 以删除扩展名,以便搜索引擎和第三方链接 - 但如果您的内部链接依赖于此,那么它可能会减慢用户和您的网站的速度,因为您正在使访问服务器的请求数量翻倍。
要删除直接请求(SEO/第三方链接)的文件扩展名,您可以这样做:
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^([^.]+)\.[\w]{2,4}$ / [R=302,L]
这确实假定 URL 路径中唯一的点是分隔文件扩展名的点。
困难的部分是在内部将请求重写回基础文件 并带有 扩展名 - 这就是 MultiViews
的用武之地(我的回答的第一部分)。