0

有没有办法自动从 url 中删除文件扩展名?

例如:

用户类型

www.website.com/page.html

它会自动将页面转换为:

www.website.com/page

如果可能的话,使用/

www.website.com/page/

.htaccess强制 url 重写文件扩展名必须是自动的。

4

3 回答 3

1

你试图以错误的方式做这件事。您不想删除扩展名。您想将无扩展名请求重写为真实文件。所以如果用户类型

http://foo.bar/file

您的服务器将按要求提供服务

http://foo.bar/file.html

为此,您需要mod_rewrite(或等效的)并根据您的需要设置重写规则。相同的模块也用于使 URL 看起来更好,所以而不是

http://foo.bar/script.php?id=34&smth=abc

你可以有

http://foo.bar/script/id/34/smth/abc

甚至

http://foo.bar/script/34/abc

阅读更多关于 mod rewrite的内容。

于 2012-09-28T10:27:37.130 回答
0

我在 .htaccess 中使用它(index.php 正在处理页面):

RewriteRule ^home/$ index.php?page=home
// Result: http://domain.com/home/

如果你想让它更有活力:

RewriteRule ^(.*)/$ index.php?page=$1
// Result: http://domain.com/any-page/

有关请求页面时可能需要的更多数据:

RewriteRule ^(.*)/(.*)/$ index.php?page=$1&id=$2
// Result: http://domain.com/data-page/15/

如果您只想获取没有索引部分的被调用页面:

RewriteRule ^(.*)/$ $1.php

要删除用户添加的扩展:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteCond %{REQUEST_FILENAME}\.html -f
于 2012-09-28T10:35:00.030 回答
0

你需要做两件事。首先,您需要将所有链接更改为不带扩展名的 URL,然后您需要创建一个 301 重定向,以将仍然可能具有带有扩展名的旧 URL 的浏览器和机器人重定向到新的漂亮 URL。这是一个新位置的服务器响应,它不是重写(这是一个仅在服务器上的内部 URI 重写)。

RewriteEngine On
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /(.*)\.(html?|php)
RewriteRule ^ /%2/ [L,R=301]

这使得当有人http://www.website.com/page.html在他们的浏览器中键入时,他们会被重定向到http://www.website.com/page/,新的 URL 将出现在浏览器的 URL 地址栏中。

现在您需要做的第二件事是在内部将其更改有效资源,因为/page/不存在,它将返回 404。

# need these so we don't clobber legit requests, just pass them through
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# now check the extensions
RewriteCond %{REQUEST_URI} ^/(.*?)/?$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^ /%1.php [L]

RewriteCond %{REQUEST_URI} ^/(.*?)/?$
RewriteCond %{DOCUMENT_ROOT}/%1.html -f
RewriteRule ^ /%1.html [L]

RewriteCond %{REQUEST_URI} ^/(.*?)/?$
RewriteCond %{DOCUMENT_ROOT}/%1.htm -f
RewriteRule ^ /%1.htm [L]

您只需要将它们放在文档根目录的 htaccess 文件中。

于 2012-09-28T19:22:27.343 回答