.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和名称的地方,每当我点击该文章链接时,我的网站就会加载,但php-Get变量丢失,因此页面不会显示文章信息(意味着文章id和名称丢失,所以页面不会收集信息(。我试过在.htaccess中重写代码,但这是我点击文章时发现的唯一一个没有以404错误结束的代码。我已经被卡住一段时间了,请让我知道我能做些什么来解决这个问题,谢谢。

ReWriteRule

重写规则的结构通常为:

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

最新更新