当我的客户端向站点添加页面时,新的页面名称应附加到RewiteRule正则表达式中。因此,例如fwrite(),我希望PHP使用从数据库中收回的值来更改RewiteRule正则表达式。如果可以做到这一点,那么在这个过程中有什么陷阱吗?
编辑:在PHP脚本中处理将是解决方案,如果没有更多的话...... 第一个域/索引.php?page=pagename 是 301 重定向到"域/页面名称" 为了警告访问者,此页面已永久移动 - (这是旧的 URL的公共位置,应该给出这个301)。然后请求 像"域名/页面名称"(新的公共位置),将是 静默地,内部重写为域/索引.php?页面=页面名称 其中 进行验证,并在无效时给出 404。但只是 键,?page=pagename的"页面"部分,是静态的,可以是 已验证,并将直接从 .htaccess 中给出 404 .现在 像domain/index.php?page=crap这样的请求首先会很好地给出301 就像有效的域/索引一样.php?页面=页面名称,并且仅在以下情况下 到达索引.php可以识别为废话。所以还有 需要将页面名称从数据库获取到 .htaccess 内部。
这是 .htacces 内容的示例,用于提供此问题的一些背景信息:
ErrorDocument 404 http://localhost/testsite/404.php
RewriteEngine on
RewriteBase /testsite/
## block craprequests without extension like domain/crap > 404
# The requests domain/pagename that do not go to existing pages, will now be redirected with a 302 to index.php?page=pagename and only then give a 404 through the errorcheck in the code.
# This should be done here, with a RewriteCond regex with database content
RewriteCond %{REQUEST_URI} !404.php$
RewriteRule .* 404.php [R=404,L]
## block-direct-queries ##
RewriteCond %{QUERY_STRING} !marker=1$
RewriteCond %{QUERY_STRING} page=(.*)
RewriteRule ^.*$ %1? [R=301,L]
## strip-extensions ##
RewriteCond %{QUERY_STRING} !.
RewriteCond %{REQUEST_URI} !404.php$
RewriteRule ^(['w+%*'d*'+*'-*]+)'.(php['s]{0,3}|htm['s]{0,3}|html['s]{0,3})$ $1 [R=301,L]
## put-querystring
RewriteRule ^(['w'-_]+)'/?$ index.php?page=$1&marker=1 [L]
抱歉继续向您重复这一点,但是不需要将页面名称存储在.htaccess中。这一切都可以在 PHP 中更简单地完成。
您需要的唯一重写规则是:
RewriteCond %{REQUEST_URI} !^/?index'.php$
RewriteRule .* /index.php [L,QSA]
现在,在 PHP 中,你可以做这样的事情:
// The important point here is that $_SERVER['REQUEST_URI'] contains the actual
// path the user typed into their browser, which is what you are interested in
if (strtolower(basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) === 'index.php') {
// The user directly requested index.php
if (!empty($_GET['page']) || value_of_page_is_crap()) {
// The user requested a bad page
header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found");
} else {
// Redirect to correct URL
header("{$_SERVER['SERVER_PROTOCOL']} 301 Moved Permanently");
header("Location: http://{$_SERVER['HTTP_HOST']}/{$_GET['page']}");
}
exit;
}
// The request is allowed to continue
$requestedPage = pathinfo($_SERVER['REQUEST_URI'], PATHINFO_FILENAME);
.htaccess将通过PHP盲目地路由每个请求,其中可以使用比mod_rewrite笨拙的基于PCRE的规则更精确的逻辑。
PHP 脚本检查用户在浏览器中的地址栏中键入的 URI。如果他们直接请求index.php
,它将检查$_GET['page']
是否包含合理的值,如果是,则将它们重定向到正确的URL,如果没有响应404。如果用户没有直接请求索引.php则脚本可以继续。我添加了一个示例行来显示如何提取他们请求的页面的值,但如何从这里继续取决于您。
这很可能是可能的(尽管写入权限可能是一个问题)。但是,通过index.php文件路由来自客户端的所有请求并让PHP处理路由不是更好的方法。
这样,您将具有最大的灵活性,并且不必做"黑客"的事情。
编辑
所有形式的重定向都可以从PHP完成,例如301
重定向的示例:
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: http://example.com/new/path'); // note the full address
exit();
有关使用header()
的更多信息,请参阅手册。