我想隐藏像 stackoverflow 这样的页面扩展。以下如何工作?
http://stackoverflow.com/tags/foo
http://stackoverflow.com/tags/bar
我见过很多这样做的网站,但我仍然不知道这是如何完成的(我有一个 LAMP 堆栈)。
我想隐藏像 stackoverflow 这样的页面扩展。以下如何工作?
http://stackoverflow.com/tags/foo
http://stackoverflow.com/tags/bar
我见过很多这样做的网站,但我仍然不知道这是如何完成的(我有一个 LAMP 堆栈)。
当 Web 服务器收到对 URL 的请求时,它必须决定如何处理它。经典的方法是将 URL 的头部映射到文件系统中的目录,然后让 URL 的其余部分导航到文件系统中的文件。因此,URL 具有文件扩展名。
但是没有必要这样做,而且大多数新的 Web 框架都不需要。它们让程序员定义如何将 URL 映射到要运行的代码,因此不需要文件扩展名,因为没有单个文件提供响应。
在您的示例中,没有包含文件“foo”和“bar”的“tags”目录。“标签” URL 被映射到使用 URL 的其余部分(“foo”或“bar”)作为针对标签数据数据库的查询中的参数的代码。
您想要的是干净的 URL,您可以使用 apache 和 .htaccess 来实现。可能有更好的方法,但这是我一直在做的:
这就是ASP.NET MVC的魅力和工作。
没有“隐藏”——这只是 ASP.NET MVC 处理 URL 并将这些“路由”映射到控制器类上的控制器操作的方式。
与“经典”的 ASP.NET Webforms 做事方式相去甚远。
在 Apache+PHP 下有几种方法可以做到这一点,但基本原则是制作一组 URI(可能是所有 URI,取决于您的站点,但您可能需要不同的脚本来处理站点的不同部分)翻译到单个 PHP 文件,该文件被告知用户请求的对象。
概念上最简单的方法是将每个 URL 重写为一个脚本,该脚本通过该 URI$_SERVER['REQUEST_URI']
并根据需要对其进行解释。
URI 重写可以使用各种方法完成,包括 mod_rewrite、mod_alias 和 ErrorDocument(请参阅 Apache 文档)。
另一种方法是设置更复杂的 URL 重写(可能使用 mod_rewrite)以将路径添加为 GET 变量。
还有一个$_SERVER['PATH_INFO']
变量加载了路径中不存在的部分。此选项几乎不需要修改 Apache 配置文件,但会稍微降低 URL 的灵活性。
现代 Web 开发框架支持优雅的 url。查看Django或Ruby on Rails。
如果您使用的是 Apache,并且只想隐藏静态 HTML 文件的文件扩展名,则可以使用以下.htaccess
代码:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f # if the requested URL is not a file that exists
RewriteCond %{REQUEST_FILENAME} !-d # and it isn't a directory that exists either
RewriteCond %{REQUEST_FILENAME}\.html -f # but when you put ".html" on the end it is a file that exists
RewriteRule ^(.+)$ $1\.html [QSA] # then serve that file
</IfModule>
Apachemod_rewrite
被称为“voodoo,但非常酷的 voodoo”。
我在一些网站上使用的实际.htaccess
代码是这样的,但并不完全相同:
<IfModule mod_rewrite.c>
RewriteEngine on
#RewriteRule ^$ index.php [QSA]
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1\.php [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php/$1 [QSA]
</IfModule>
这里有一些更长但更易读的代码,可以在 Zeus 服务器上做同样的事情。在宙斯上,它被称为rewrite.script
.
# http://drupal.org/node/46508
# get the document root
map path into SCRATCH:DOCROOT from /
# initialize our variables
set SCRATCH:ORIG_URL = %{URL}
set SCRATCH:REQUEST_URI = %{URL}
match URL into $ with ^(.*)\?(.*)$
if matched then
set SCRATCH:REQUEST_URI = $1
set SCRATCH:QUERY_STRING = $2
endif
# prepare to search for file, rewrite if its not found
set SCRATCH:REQUEST_FILENAME = %{SCRATCH:DOCROOT}
set SCRATCH:REQUEST_FILENAME . %{SCRATCH:REQUEST_URI}
# check to see if the file requested is an actual file or
# a directory with possibly an index. don't rewrite if so
look for file at %{SCRATCH:REQUEST_FILENAME}
if not exists then
look for dir at %{SCRATCH:REQUEST_FILENAME}
if not exists then
look for file at %{SCRATCH:REQUEST_FILENAME}.php
if exists then
set URL = %{SCRATCH:REQUEST_URI}.php?%{SCRATCH:QUERY_STRING}
else
set URL = /index.php/%{SCRATCH:REQUEST_URI}?%{SCRATCH:QUERY_STRING}
endif
endif
endif
goto END