URL重写以清理扩展名

时间:2013-05-29 09:15:07

标签: php html apache mod-rewrite dns

我正在寻找RewriteRule来清理URL。我已经有一条规则可以找到只有/file而不是/file.ext的网页。问题是,当输入/file.ext这样的页面时,它将等于/file我想要的页面。

现在我意识到这会让事情变得更难,因为在设置链接时我需要设置它而不需要扩展。反过来,设置原始文件名包括更容易。扩展和设置apache以重写/删除扩展名。

如果有人可以帮助我,那就太好了。常见的扩展名是php,html和htm。

非常感谢。

2 个答案:

答案 0 :(得分:0)

我猜每个扩展都需要一套规则。您可以在根目录下的一个.htaccess文件中尝试此操作:

Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /

## Option using html extension
# Check if it is to a file without query
RewriteCond %{THE_REQUEST} /([^.]+)\.html\s [NC]
# Remove the extension and show the name at the browser's address bar
RewriteRule  .*  /%1  [R=301,L,NC]

# Prevent loops
RewriteCond %{REQUEST_URI} !\.html  [NC]
# Map silently to the original file
RewriteRule  ^([^/]+)/?  /$1.html  [L,NC]

重复最后4行,相应地修改扩展的所有实例。

答案 1 :(得分:0)

您要搜索的答案如下:.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才会跟进。为了为文件扩展名添加更多过滤器,效率会降低。