php - .haccess 链接重写,新链接丢失 php 获取变量
问题描述
在我的网站上,我试图改变我的链接:
example.com/news/foobar.php?id=21&artName=Hello-World
看起来像这样:
example.com/news/foobar/21/Hello-World
在我的 .htaccess 文件中,我有以下代码:
<FilesMatch "^\.htaccess">
Order allow,deny
Deny from all
</FilesMatch>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?(.*)/(.*)$ ^news/foobar.php?id=$1&artName=$2 [NC,L,QSA]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*) $1.php [L]
我的文章链接如下所示:
<a href="https://www.example.com/news/foobar/'.$row['id'].'/'.$row['linkAddress'].'" class="post-title">'.$row['aName'].'</a>
它从变量中收集 id 和 name,每当我单击该文章链接时,我的网站就会加载,但缺少 php Get 变量,因此页面不显示文章信息(意味着缺少文章 id 和名称,因此页面不收集信息)。我曾尝试在我的 .htaccess 中重写代码,但这是我发现的唯一一个在单击文章时没有以 404 错误结尾的代码。我已经卡了一段时间了,请告诉我我能做些什么来解决这个问题,谢谢。
解决方案
重写规则
重写规则的结构通常是:
ReWriteCond SOME_CONDITION
ReWriteRule REGEX_FOR_INPUT_STRING OUTPUT_STRING [FLAGS]
在您的情况下,我们并不严格需要条件,因此我们可以跳到重写规则:
RewriteRule ^news/foobar/(\d+)/([\w-]+)/?$ news/foobar.php?id=$1&artName=$2 [NC,L,NE]
解释
// Matching Regex:
^news/foobar/(\d+)/([\w-]+)/?$
^ : Matches the start of the string
news/foobar/ : Matches the first two "directories" in the URL
(\d+) : Capture group 1 to get the id
/ : Matches a slash between id and artName
([\w-]+) : Capture group 2 to capture artName
/? : Matches an optional closing /
$ : Matches the end of the string
// Replacement:
news/foobar.php?id=$1&artName=$2
news/foobar.php? : Path to file and start of query string (?)
id=$1 : First query parameter ($1 is a call back to capture group 1)
& : & goes between parameters in the query string
artName=$2 : Second query parameter ($2 is a call back to capture group 2)
// Flags:
[NC,L,NE]
NC : Makes the match case insensitive
L : Stops the .htaccess from applying further rules
NE : Stops the rewrite escaping the & in the query string.
Without it & would become %26
边注
请记住,现在,当导航到您使用的页面时,您使用的 url 如下:
example.com/news/foobar/21/Hello-World
<a href="example.com/news/foobar/21/Hello-World">Click me!!</a>
在 PHP 中你仍在使用$_GET
:
echo $_GET["id"]; // 21
echo $_GET["artName"]; // Hello-World
推荐阅读
- c# - Blazor 显示没有验证属性的验证消息
- c++ - 如何创建具有相同构造函数但名称不同的类?
- pandas - 更改数据框中某些列名的类型
- typescript - 如何正确键入从 Record<> 扩展的接口的交集?
- testing - TestCafe - 如何在非 Chrome 浏览器中运行并显示测试执行
- python - 无法通过 pydrive 对谷歌驱动器进行身份验证
- c - toLower C 中的字符串 0xC0000005
- java - UML 对象图:父或子
- airflow - Apache Airflow (2.0.0b1) - 动态创建任务并在函数中访问 kwargs
- python - 如何使用 discord.py 检索以前的消息