我想用htaccess重写参数到路径。
示例: https://test.link?test123 -> https://test.link/test123
该网站正在使用 PHP 8.0 运行。
我的 .htaccess 中有以下可在本地主机上运行的代码:
RewriteEngine on
[...]
RewriteCond $1 !^(index\.php)
RewriteCond ${REQUEST_FILENAME} !-f
RewriteCond ${REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
但是由于我在 Hostinger 上托管,所以这不起作用。 所以我的问题是我是否需要启用/禁用某些插件或某些东西,或者它只是被 Hostinger 以某种方式阻止了?
如果它对任何人有帮助,这是我的index.php:
<?php
require_once 'ga_linked_database.php'; #just connecting to the DB, works fine
$new_uri = "";
if(!empty($_GET)){
foreach($_GET as $key => $val){
$u = $key;
$new_uri = str_replace('/', '', $u);
$sql = "[...]";
$stmt = mysqli_stmt_init($connect);
if(mysqli_stmt_prepare($stmt, $sql)){
mysqli_stmt_bind_param($stmt, "s", $new_uri);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
$resultnum = mysqli_num_rows($resultData);
if($resultnum > 0){
$c_query = "[...]";
$stmts = mysqli_stmt_init($connect);
if(mysqli_stmt_prepare($stmts, $c_query)){
mysqli_stmt_bind_param($stmts, "s", $new_uri);
mysqli_stmt_execute($stmts);
mysqli_stmt_close($stmts);
}else{
echo "<h1>Error</h1>";
http_response_code(500);
exit();
}
if($row = mysqli_fetch_assoc($resultData)){
$long_url = $row["long_url"];
header("Location: " . $long_url);
}else{
echo "<h1>Error - unknown error</h1>";
exit();
}
}else{
echo "<h1>Error</h1>";
exit;
}
mysqli_stmt_close($stmt);
}else{
http_response_code(500);
echo "<h1>Error</h1>";
exit();
}
}
}else{
echo "<h1>File / not found</h1>"
exit;
}
?>
(不要评判我的PHP代码,这只是我自己的一个项目)
我必须对我的 PHP 代码和
.htaccess
文件进行调整,因为我之前做过类似的事情,并且由于 .htaccess
行为随服务器设置而变化(在我的实例中),因此出现了稍微类似的问题。只是为了提醒您,即使您说“不要评判我的代码”,事实是,这是获得您想要的结果的糟糕方法。我确信有许多更优雅的方法可以实现您的目标。经过 X 时间并且我获得了一些经验后,我必须“更新”我的这个项目,尽管我留下了很多评论和解释我在哪里做了什么,但我打了自己的头,因为我几乎不明白任何东西。
无论如何,试试这个:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^(.+)$
RewriteRule ^/?$ /%1? [R=301,L]
这条规则的运作方式如下:
RewriteCond %{QUERY_STRING} ^(.+)$
行确定是否存在非空查询字符串。
RewriteRule ^/?$ /%1? [R=301,L]
行将根 URL (/
) 重写为包含查询字符串(由 %1
捕获)的路径。末尾的 ?
会从重写的 URL 中删除原始查询字符串,R=301
表示永久重定向,L
表示这是满足条件时将执行的最终规则。
设置完成后
.htaccess file
,您的 PHP 脚本将以路径格式获取请求。例如,对 https://test.link?test123 的请求将被重建为 https://test.link/test123。
然后,您的 PHP 脚本必须解析 URL 路径,而不是解析查询字符串。
require_once 'ga_linked_database.php';
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$pathComponents = explode('/', trim($path, '/'));
$new_uri = $pathComponents[0]; // With asumption that first component is what you need... after this goes rest of your code
--使用
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH).
explode('/',trim($path,'/')).
$pathComponents[0]
获取路径的初始组件,在原始查询参数的情况下为 test123。