PHP和htaccess |如果用户尝试直接访问url中的参数值,则重定向到“找不到页面”

问题描述

我在我的网站上有一个友好的网址:

https://myexample.com/post/10/post-title

我正在尝试做一些拒绝用户直接在参数值中访问的操作。例如,如果用户尝试在上面的url中放置另一个id,则htaccess会将其重定向到404页面。

下面是我的htaccess代码,该代码将我的url获取参数转换为友好的url并像超级按钮一样工作:

RewriteEngine On
RewriteRule ^post/([^/]*)/([^/]*)$ /news?id=$1&title=$2 [L]

在这种情况下,如何改善htaccess的访问权限?

任何帮助,我都会感激。

解决方法

我找到了解决问题的方法,并且效果很好:

我的.htaccess:

RewriteEngine On
RewriteRule ^post/?(.*)/([^/]*)$ /news?id=$1&title=$2 [L]

首先,我实现了一个函数,用于替换news.php上 title 参数上的空格和特殊字符:

function sanitizeString($str) {
    $str = preg_replace('/[áàãâä]/ui','a',$str);
    $str = preg_replace('/[éèêë]/ui','e',$str);
    $str = preg_replace('/[íìîï]/ui','i',$str);
    $str = preg_replace('/[óòõôö]/ui','o',$str);
    $str = preg_replace('/[úùûü]/ui','u',$str);
    $str = preg_replace('/[ç]/ui','c',$str);
    $str = preg_replace('/[^a-z0-9]/i','-',$str);
    $str = preg_replace('/_+/',$str);
    return $str;
}

然后我在news.php上创建了一个脚本,该脚本检查 id title 参数在MySql上是否正确相关:

include 'connection.php';

$stmt = $db -> prepare('SELECT id,title FROM posts WHERE id = ?');

$id = $_GET['id'];

$stmt -> bind_param('i',$id);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($postID,$title);
$stmt -> fetch();
$stmt -> close();
$db -> close();

$postTitle = sanitizeString(trim(strtolower($title)));

if($_GET['id'] != $postID || $_GET['title'] != $postTitle){
    
    header('location: /404.html');
    exit();
    
}else{
    
    echo 'Everything Fine';
    
}

基本上,根据上面的代码,如果用户尝试操纵URL中的参数,例如 id / 10 /和 title / post-title:

https://myexample.com/post/10/post-title

例如,脚本会将用户重定向到404错误页面或找不到页面或某些自定义页面。

如果有人有更好的方法可以改善这一点,请在此处告知。

希望这个问题可以帮助其他人。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...