【问题标题】:URL rewriterule to clean extensionsURL重写以清除扩展
【发布时间】:2013-05-24 11:31:42
【问题描述】:
我正在寻找一个 RewriteRule 来清理 URL。我已经有一条规则,可以找到只有/file 而不是/file.ext 的页面。问题是当输入像/file.ext 这样的页面时,它将等于我想要的/file。
现在我意识到这让事情变得比实际更难,因为在设置链接时,我需要在不扩展的情况下设置它们。否则,设置原始文件名(包括)会容易得多。扩展并设置 apache 重写/删除扩展。
如果有人可以帮助我,那就太好了。常见的扩展有php、html和htm。
非常感谢。
【问题讨论】:
标签:
php
html
apache
mod-rewrite
dns
【解决方案1】:
您正在寻找的答案在这里:.htaccess file extension removal not working (lots of solutions tried)
请参阅接受的答案,它基于 .shtml 文件扩展名。您必须为要使用的每个文件扩展名复制这些规则,并将 .shtml 替换为文件扩展名。
小心:如果您有两个文件 index.html 和 index.php 并且您使用 .php 和 .html 的规则,只有第一个匹配有效。所以为不同的文件选择不同的文件名。
RewriteEngine on
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s.+\.html [NC]
RewriteRule ^(.+)\.html$ /$1 [R=301,L,NC]
# To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_URI} !\.html$ [NC]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule . %{REQUEST_URI}.html [L]
# To externally redirect /dir/foo.htm to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s.+\.htm [NC]
RewriteRule ^(.+)\.htm$ /$1 [R=301,L,NC]
# To internally redirect /dir/foo to /dir/foo.htm
RewriteCond %{REQUEST_URI} !\.htm$ [NC]
RewriteCond %{REQUEST_FILENAME}.htm -f
RewriteRule . %{REQUEST_URI}.htm [L]
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s.+\.php [NC]
RewriteRule ^(.+)\.php$ /$1 [R=301,L,NC]
# To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_URI} !\.php$ [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule . %{REQUEST_URI}.php [L]
还要注意,这仍然是一种“低效”。对于发送到服务器的每个请求,例如 /file,它首先会尝试查找 file.html。如果它没有找到它,它将寻找 file.htm。如果它没有找到它,它将寻找file.php。只有在它没有找到file.php之后,404才会跟随。为文件扩展名添加更多过滤器会增加效率。